Mike
Mike

Reputation: 5788

Vuejs 2: Change second select list according to first

I want to change the second select list according to the selected value in the first one. It worked when i did two Vue instances for each select, but i wanted to do a small app so its all a bit cleaner.

The types JSON array needs to be outside the Vue JS. You can see it in the fiddle.

Somehow i just dont get how to update the second selectlist.

Before i did something like this and it worked perfectly:

// methods of first select (category)
methods: {
  update: function (value)
     this.options = types[value]
  }
}

...

// methods of second select (typselect)
methods: {
  onChange(event) {
    typselect.update(event.srcElement.value)
  }
}

The app:

<div id="app">

  <select v-model="category" v-on:change="onChange">
    <option>Choose</option>
    <option value="5">type1</option>
    <option value="6">type2</option>
    <option value="11">type3</option>
  </select>

  <select id="typselect">
    <option v-for="option in options" v-bind:value="option.value">{{ option.text }}</option>
  </select>

</div>

So i switched that for something like this:

new Vue({
  el: '#app',

  data: {
    category: '5'
  },

  computed: {
    options: function(event) {
      console.log('should be called on change');

      let options = ''
      options = 1;
      //  options = types[event.srcElement.value]; // this would be so easy...
      return options
    }
  },

  methods: {
    onChange: function(e) {
      console.log(event.srcElement.value);
      this.options = this.options
    }
  }
})

But i just don't get how to get the second selectlist updated.

Here come a fiddle: https://jsfiddle.net/Honkoman/g9g5uukr/2/

Upvotes: 2

Views: 4192

Answers (1)

Bert
Bert

Reputation: 82439

Your computed should look like this.

computed: {
  options: function(event) {
    return types[this.category]
  }
},

Updated fiddle.

Upvotes: 3

Related Questions