Search code examples
vue.jsquasar

How can I change selected item in qselect on page load


I use a QSelect Dropdown with some options on my page header, like the following:

<q-select
      filled
      v-model="model"
      use-input
      hide-selected
      fill-input
      input-debounce="0"
      :options="options"
      @filter="filterFn"
      hint="Basic autocomplete"
      style="width: 250px; padding-bottom: 32px"
      emit-value
      map-options
    >
      <template v-slot:no-option>
        <q-item>
          <q-item-section class="text-grey">
            No results
          </q-item-section>
        </q-item>
      </template>
    </q-select>

    const stringOptions = [
  {label:'Google', value:'g1111111111'},  {label:'Facebook', value:'f2222222222'}, {label:'Twitter', value:'t3333333'}, {label:'Apple', value:'a44444444'}, {label:'Oracle', value:'o555555555'}
]

new Vue({
  el: '#q-app',
  data () {
    return {
      model: 'f2222222222',
      options: stringOptions
    }
  },

  methods: {
    filterFn (val, update, abort) {
      update(() => {
        const needle = val.toLowerCase()
        this.options = stringOptions.filter(v => v.label.toLowerCase().indexOf(needle) > -1)
      })
    }
  }
})

How can I use a method to change the selected value on pageload for example from facebook to google?

I think with something like the following but cant get it working:

  mounted: function () {
    this.model = 'g1111111111'
  },

codepen: https://codepen.io/aquadk/pen/JQbbKw

Thanks


Solution

  • You can use updated method, it called after the data changed and virtual dom is created for that component. Then you can update the value of the model.

    const stringOptions = [  
    
    {label:'Google', value:'g1111111111'},  {label:'Facebook', value:'f2222222222'}, {label:'Twitter', value:'t3333333'}, {label:'Apple', value:'a44444444'}, {label:'Oracle', value:'o555555555'}
    ]
    
    new Vue({
      el: '#q-app',
      data () {
        return {
          model: 'f2222222222',
          options: stringOptions
        }
      },
    
      methods: {
        filterFn (val, update, abort) {
          update(() => {
            const needle = val.toLowerCase()
            this.options = stringOptions.filter(v => v.label.toLowerCase().indexOf(needle) > -1)
          })
        }
      },
      updated(){
          // Update the value of model
          this.model = 'g1111111111';
      }
    })