[Vuejs]-I want to dynamically create new instances of a Vue component with information attached to each of them. What's wrong with my code?

2👍

A lot of what you are doing is Vue 1 syntax, but you are using Vue 2, so firstly:

The ready() lifecycle hook has been deprecated, and you now use created():

created: function() {
    this.$http.get(API_TYPES).then(function(types) {
        this.$set('types', types.body)
    });
}

Interpolation inside attributes has also been removed, essentially you cannot use handlebars (or need to) when assigning model data to an attribute (it’s still fine in HTML), so, you should remove the handlebars for value and use v-bind instead (you can also just use a colon as a shorthand for v-bind e.g. :value="type.value"):

<select @change="switchType">
    <option v-for="type in types" v-bind:value="type.value">@{{ type.text }}</option> 
</select>

I personally would bind my select boxes using v-model, rather than trying to manually handle the change, but without seeing your entire project, I couldn’t say for sure that this would be appropriate for your project, but basically you bind each select box to an element of an array:

Markup

  <select v-model="selected[0]">
    <option v-for="type in types" v-bind:value="type.value" v-text="type.text"></option>
  </select>
  
    <select v-model="selected[1]">
    <option v-for="type in types" v-bind:value="type.value" v-text="type.text"></option>
  </select>

View Model:

var vm = new Vue({
  el: '#app',
  data: {
    types: [{
      value: 'foo',
      text: 'foo'
    }, {
      value: 'bar',
      text: 'bar'
    }, {
      value: 'baz',
      text: 'baz'
    }],
    selected: []
  }
})

And if you wanted to do something when the selection changes you could just add a watcher to that:

  watch: {
    selected: function(val){
      // do something
      console.log('selected updated to: ' + val);
    }
  }

Here’s the JSFiddle for that: https://jsfiddle.net/utf169mw/

If you get stuck on anything else Vue has a migration guide at: https://v2.vuejs.org/v2/guide/migration.html

You can find the 2.0 docs at: https://v2.vuejs.org/v2/guide/

And of course you can ask here, also remember to check your console under your browsers developer tools, because Vue will generally tell you what the problem is.

Leave a comment