Vuejs 2.0 dynamic component

Adding and removing dynamic components

by Edward Tanguay

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="app">
  {{ sections }}
  <fruit :fruits="fruitItems" v-for="(section, index) in sections" @remove="removeSection(index)" :section="section"></fruit>

  <button type="button" v-on:click="addComponent()">Add New Component</button>
</div>


<div id="dropdown1">
  <div>
    	<select v-model="section.fruit">
    		<option v-for="item in myFruits" :value="item.name">{{ item.name }}<option>
    	</select>
    	<button type="button" v-on:click="$emit('remove')">Remove Me {{ section.id }}</button>
      selected222: {{section.fruit}}
  </div>
</div>

JavaScript

Vue.component('fruit', {
  template: '#dropdown1',
  props: ['fruits', 'section'],
  data: function() {
    return {
      myFruits: this.fruits
    }
  }
});

var vm = new Vue({
  el: '#app',
  data: function() {
    return {
      fruitItems: [{
        name: "Banana"
      }, {
        name: "Mango"
      }, {
        name: "Apple"
      }, ],
      sections: [{
        id: "1",
        fruit: ''
      }]
    }
  },
  methods: {
    removeSection: function(index) {
      this.sections.splice(index, 1)
    },

    addComponent: function() {
      this.sections.push({
        id: Math.floor(Math.random() * 6),
        fruit: ''
      });
    }
  }
})