How can I set option value selected in v-select in vue.js 2?

Rashed Hasan picture Rashed Hasan · Feb 7, 2019 · Viewed 7.3k times · Source

I am trying to set option selected where option value is 1. But I am getting in trouble when using v-select from vuejs. This is how I am trying to do -

<v-select name="branchid" v-model="branchid" 
         :options="branches.map(branches => ({label: branches.label, value: branches.value}))" 
         :selected="branches.value === 1"></v-select>

Would someone help me please to get the option value selected when option value is 1?

Answer

Marcus picture Marcus · Feb 8, 2019

I've put together a simplified version of what (I think) you're trying to do:

<template>
  <div>
    <div>
      <select v-on:change="select($event);" value="branchid">
        <option disabled value="">Please select one</option>
        <option :selected="branchid === 1">1</option>
        <option :selected="branchid === 2">2</option>
        <option :selected="branchid === 3">3</option>
      </select>
      <span>Selected: {{ branchid }}</span>
      <button v-on:click="selectOne">Select Option 1</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      branchid: 0,
      branchidTwo: 1
    };
  },
  methods: {
    select: function(evt) {
    this.branchid = evt.target.value;
  },
    selectOne: function() {
      this.branchid = 1;
    }
  }
};
</script>

This does not use the v-model pattern. The docs explicitly state that if you use v-model, the class itself will be used as the source of truth rather than value or selected. You'll see I've added a button that will set the selected option on the select component.

Hope that helps.