How to set v-select value dynamically?

Viewed 29000

My Vuetify v-select element looks this way:

<v-select
   v-bind:items="languages"
   v-model="setLocale"
   label="Language:"
   auto prepend-icon="map"
   item-value="fetchedLocale"
   hide-details
   id="langSelect"
   >

In data you can find:

data () {
  return {
    languages: [
      { shortCode: 'en', text: 'English' },
      { shortCode: 'pl', text: 'Polski' },
      { shortCode: 'es', text: 'Español' },
      { shortCode: 'pt', text: 'Portugues' }
    ],
    fetchedLocale: '',
    setLocale: null
  }
}, (...)

After some processing, fetchedLocale gets value of some of text properties from the array above, e.g. "Portugues".

Question: how to update the v-select so that it sets fetchedLocale's value, like mentioned before "Portugues", when loading DOM elements, instead of setting default empty value?

1 Answers

As per the documentation, the item-value prop defines the property name to use as the value for each item. The default for this prop is 'value', meaning the value property of each item will be used as each item's value by default. If you set it to text, for example, then the text property of each of your languages will be used as the value of that item. However, this won't actually set the value of the select component.

You've already bound the value of the select component to setLocale via v-model. So if you want to change the select component's value to the fetchedLocale value, just update setLocale with the value of fetchedLocale and the component will update:

this.setLocale = this.fetchedLocale

Here's a working example:

new Vue({
  el: '#app',
  data() {
    return {
      languages: [
        { shortCode: 'en', text: 'English' },
        { shortCode: 'pl', text: 'Polski' },
        { shortCode: 'es', text: 'Español' },
        { shortCode: 'pt', text: 'Portugues' }
      ],
      fetchedLocale: '',
      setLocale: null
    };
  },
  created() {
    setTimeout(() => {
      this.fetchedLocale = 'English';
      this.setLocale = this.fetchedLocale;
    }, 1000);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<script src="https://unpkg.com/vuetify@0.15.7/dist/vuetify.js"></script>
<link href="https://unpkg.com/vuetify@0.15.7/dist/vuetify.min.css" rel="stylesheet"/>
<link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet" type="text/css">

<div id="app">
  <v-app>
    <v-select
      :items="languages"
      v-model="setLocale"    
      label="Language:"
      auto prepend-icon="map"
      item-value="text"
      hide-details
      id="langSelect"
    ></v-select>
  </v-app>
</div>

Related