Search code examples
javascriptvue.jsvuejs2vuetify.jsv-autocomplete

How to dynamically format date on item-text inside v-autocomplete (Vuetify)


I have this v-autocomplete which receives an array of items to display from GrowthTasks.edges

<v-autocomplete label="Start Week" 
:items="GrowthTasks.edges" item-text="node.growthStartDate" item-value="node.growthStartDate" dense></v-autocomplete>

The item-text receives the text from there by acessing node.growthStartDate, which is a date format like : "2020-05-06".

Now I want to turn it into a format like "2020-W19" , which I know is possible using moment("YYYY-[W]WW") but I dont know how to tell this to item-text.

Basically, I want the result on the item-text to be the same as if I was using :

{{ node.growthStartDate | moment("YYYY-[W]WW") }}

which works.

Any idea on how can do it ?


Solution

  • You can create computed property and return formated dates:

    new Vue({
      el: '#app',
      vuetify: new Vuetify(),
      data() {
        return {
          GrowthTasks: {edges: [{growthStartDate: "2020-05-06"}, {growthStartDate: "2020-06-07"}]}
        }
      },
      computed: {
        items() {
          return this.GrowthTasks.edges.map(obj => ({ ...obj, growthStartDate: moment(obj.growthStartDate).format("YYYY-[W]WW") }));
        }
      }
    })
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <div id="app">
      <v-app>
        <v-main>
          <v-container>
            <v-autocomplete label="Start Week" 
    :items="items" item-text="growthStartDate" item-value="growthStartDate" dense></v-autocomplete>
          </v-container>
        </v-main>
      </v-app>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>