Léo Coco
Léo Coco

Reputation: 4282

Vue.js - Reactivity of a select whose value is the selected object and not its id

I'm using vue.js 2.3 and element-ui. I'm facing reactivity issues with a select dropdown whose value is the item picked.

Problems

The select is not automatically filled with the initial object value

Notices

If I change :value="item" to :value="item.name"

and form: {option: {name:'blue', price: ''}} to form: {option:'blue'}

It is working

Questions

Is there a way to make the select dropdown fully reactive when its value is not just a string or a id but rather the whole object that has been selected

https://jsfiddle.net/LeoCoco/aqduobop/

<

div style='margin-bottom:50px;'>
My form object : 
  {{form}}
</div>

  <el-button @click="autoFill">Auto fill</el-button>

  <el-select v-model="form.option" placeholder="Select">
    <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item">
    </el-option>
  </el-select>
</div>


    var Main = {
    data() {
      const options = [
     {name: 'blue', price: '100$'},{name: 'red', price: '150$'},
      ]

      return {
        currentItem: 0,
        options,
        form: {
            option: {name:'', price: ''},
        },
         testForm: {
            option:{name:'red', price: '150$'}
        },
      }
    },
    methods: {
      autoFill() {
        this.form =  Object.assign({}, this.testForm); // -> Does not work
      }
    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

Upvotes: 1

Views: 2610

Answers (1)

Bert
Bert

Reputation: 82459

Your issue is that when the selected value is an object, then form.option needs to be the same object in order for it to be selected in the select list.

For example if I change the fiddle code to this, I think it works the way you expect.

var Main = {
    data() {
      const options = {
        'color': [{name: 'blue', price: '100$'},{name: 'red', price: '150$'}],
        'engine': [{name: '300hp', price: '700$'},{name: '600hp', price: '2000$'}],
      }
      let currentCategory = 'color'

      return {
        currentCategory,
        currentItem: 0,
        options,
        form: {
            option: options[currentCategory][0]
        },
         testForm: {
            option:{name:'blue', price: '100$'}
        },
      }
    },
    methods: {
      autoFill() {
        this.form =  Object.assign({}, this.testForm); // -> Does not work
      }
    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

Here is your fiddle updated.

You said your values are coming from an ajax call. That means that when you set form.option you need to set it to one of the objects in options[currentCategory].

Upvotes: 1

Related Questions