Selecting only the month and year with the v-date-picker

I am looking for an alternative approach using the v-date-picker component. My requirement is to allow users to only select the year and month, and then close the date picker menu automatically.

Below is an example of my HTML code, but I am open to using different code as long as it incorporates the v-date-picker functionality:

<v-menu v-model='monthMenu'
        :close-on-content-click='false'
        :nudge-right='40'
        transition='scale-transition'
        offset-y
        min-width='290px'>
  <template v-slot:activator='{ on, attrs }'>
    <v-text-field v-model='txtMonth'
                  label='Month'
                  prepend-icon='mdi-calendar'
                  readonly
                  v-bind='attrs'
                  v-on='on'
    ></v-text-field>
  </template>
  <v-date-picker v-model='month'
                 @change='datePicked'
                 color='primary'
                 scrollable
  ></v-date-picker>
</v-menu>

The ts file contains the datePicked method where I have attempted some solutions that did not work as expected:


export default Vue.extend({
  data() {
    return {
      monthMenu: false,
      month: new Date(new Date().getFullYear(), new Date().getMonth()).toISOString()
        .substr(0, 10),
    };
  },
  computed: {
    txtMonth(): string {
      const [year, month, day] = this.month.split('-');
      return `${year}/${month}/${day}`;
    },
  },
  methods: {
    datePicked(log: any) {
      /* eslint-disable */
      console.log('here2');
      // const el = document.getElementsByClassName('v-date-picker-table--month') as unknown as HTMLElement;
      const acc = document.getElementsByClassName('v-date-picker-table--month');
      let i;
      for (i = 0; i < acc.length; i++) {
        acc[i].addEventListener("click",function() {
          console.log('here');
          // this.monthMenu = false
        });
      }
    },
  },
});

Answer №1

Finally cracked the code after investing a few hours into this requirement. The trick is to monitor the value of the month model in order to close the date picker modal when necessary. Additionally, make sure to set the type attribute to month for the <v-date-picker> element.

Check out the Live Demo below:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      monthMenu: false,
      txtMonth: '',
      month: ''
    }
  },
  watch: {
      monthMenu (val) {
        val && setTimeout(() => (this.$refs.picker.activePicker = 'YEAR'))
      },
      month (val) {
        this.monthMenu = false;
      }
    },
  methods: {
    onInput(dateStr) {
      const month = dateStr.split('-')[1];
      const year = dateStr.split('-')[0];
      this.txtMonth = `${month}, ${year}`;
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbbdbeae8bf9e5b3">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e787b6b7a6768774e3c203d203f">[email protected]</a>/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e080b1b0a1718073e4c504d504f">[email protected]</a>/dist/vuetify.min.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bddbd2d3c9fd8893c5">[email protected]</a>/css/materialdesignicons.min.css"/>

<div id="app">
  <v-app id="inspire">
    <p class="mb-1">Selected: {{ txtMonth }}</p>
    <v-menu v-model='monthMenu'
            :close-on-content-click='false'
            :nudge-right='40'
            transition='scale-transition'
            offset-y
            min-width='290px'>
      <template v-slot:activator='{ on, attrs }'>
        <v-text-field v-model='txtMonth'
                      label='Month'
                      prepend-icon='mdi-calendar'
                      readonly
                      v-bind='attrs'
                      v-on='on'
                      ></v-text-field>
      </template>
      <v-date-picker v-model='month'
                     @input='onInput'
                     color='primary'
                     scrollable
                     type="month"
                     ref="picker"
                     ></v-date-picker>
    </v-menu>
  </v-app>
</div>

Answer №2

According to the insights of wimanicesir,

          <v-calendar v-model='month'
                     @modify='monthMenu = false'
                     color='blue'
                     scrollable
                     mode='monthly'
      ></v-calendar>

I incorporated mode='monthly' and eliminated the datePicked function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular Error Handler - Extracting component context information from errors

In the event of a TypeScript error, I am looking to send all of the component's attribute values to a REST API. It would greatly benefit me if I could access the component's context (this) in order to retrieve the values of all attributes within ...

Steps for submitting a form when the input value changes

I'm facing an issue with my form. I want a function to run every time the user changes a value in the input field, so I attached a small function to the form like this: onChange={() => { formRef.current?.submit(); }} However ...

Encountering Issues with TypeScript Strict in Visual Studio Code Problems Panel

I have discovered that I can optimize my TypeScript compilation process by utilizing the --strict flag, which enhances type checking and more. Typically, I compile my TypeScript code directly from Visual Studio Code with a specific task that displays the c ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

Tips for aligning a cluster of floating buttons at the center in Vuetify:

This is the code I am currently working with: <v-container height="0"> <v-row align="center" justify="center"> <v-hover v-slot:default="{ hover }" v-for="(option, index) in options" ...

The type does not contain a property named 'x' - Error in Promise syntax - TS2339

I encountered a problem while working with Typescript that I couldn't quite figure out. Although I came across similar issues in other topics, I'm still struggling to find a solution for my particular issue. I can easily log userCredential.user.m ...

Tips for designing a Quasar page that dynamically loads content as the user scrolls

I am attempting to develop a component that will render multiple elements as the page is scrolled. I am utilizing the Quasar framework for Vue.js. Below is the code required to render a single block containing information from a JSON file: Quasar comes wi ...

The websocket connection is experiencing difficulties, but socket.io is functioning properly

I am attempting to establish a websocket connection using Websocket in my Vue project, however, I consistently encounter the following error: WebSocket connection to 'wss://localhost:3000/' failed: This is the code snippet I am utilizing: onMou ...

Specify the correct type for the SVG component when passing it as a prop

Currently, I am in the process of constructing a button component: interface ButtonProps { startIcon?: ... <-- what should be the data type here? } const Button = ({startIcon: StartIcon}) => { return <button>{StartIcon && <Sta ...

Utilizing Angular 5 DataTables Plugin: Passing Data from HTML to TypeScript Function

I am currently working with the component.html code below, which is using a DataTables plugin. The issue I am facing is that when I select rows and click the Delete button, the handleDelete() function is called. However, I am unsure of how to pass the se ...

Flag is activated to retrieve the data from the @Input source

@Input() config= []; flag = false; I need to change the flag to true only when I receive data in the config from the @input. Where should I do this? The data in the config is delayed and I am unable to access it in ngOnInit but can get it in ngOnChanges. ...

Dealing with problems related to types in React and TypeScript createContext

Struggling to pass the todos (initial state) and addNewTodo (methods) using React Context hook and typescript. Despite trying multiple solutions, errors persist. Partial generics do not cause issues in the context component, but I encounter the error Cann ...

What is the method of duplicating an array using the array.push() function while ensuring no duplicate key values are

In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the ...

Managing multiple asynchronous requests through Observables in web development

I am working on an Angular2 website that sends multiple ajax requests using Json Web Tokens for authorization when it is initialized Here are two examples: public getUser(): Observable<User> { // Code block to get user data } public getFriends ...

I'm confused why this particular method within a class is not being inherited by the next class. Rather than seeing the expected extension, I am presented with - [Function (

Working fine with the Person class, the register() function displays the correct return statement when logged in the console. However, upon extending it to the Employee class, instead of the expected return statement, the console logs show [Function (anon ...

f:ajax not triggering on the "change" event

Check out the following code snippet: <h:inputText id="date" value="#{holidayRequestController.dates}"> <f:ajax execute="date" event="change" listener="#{holidayRequestController.generateDates}" ...

Learn the process of importing different types from a `.ts` file into a `.d.ts` file

In my electron project, the structure looks like this: // preload.ts import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron' import { IpcChannels } from '@shared/channelNames' contextBridge.exposeInMainWorld('api&a ...

Angular is unable to start the variable_INITIALIZation process

I've created a method called get that returns data of type ProductModel. getProduct(id:number): Observable<ProductModel[]> { const url = `${'api/product/getProductById/'}/${id}`; return this.http.get<ProductModel[]>(u ...

The application is unable to load due to a console error showing that the endpoint is unreachable

Recently, I made an upgrade from Angular 5 to 7 while still keeping rxjs-compat in place. Initially, the application was running smoothly with no issues. However, we eventually decided to remove rxjs-compat and make the necessary changes. This is when we e ...

Oops! There seems to be an issue. The system cannot locate a supporting object with the type 'object'. NgFor can only bind to Iterables

onGetForm() { this.serverData.getData('questionnaire/Student Course Review') .subscribe( (response: Response) => { this.questionnaire = response.json(); let key = Object.keys(this.questionnaire); for ...