Vue.js: input list delete/create

by Eugene Manager

HTML

<script type="x-template" id="card_template">
  <div> 
    Card
    <input v-model="param.text"/>
    <button @click="delete_me">
      Delete
    </button>
  </div>
</script>


<div id="app">
    Cards!
    <div v-for="elem in cards_array">
      <component is="card_component" :param="elem"></component>
    </div>
    <button @click="addCard()">
      New Card
    </button>
    <pre>{{ $data }}</pre>
</div>

JavaScript

Vue.component('card_component', {
	props: ['param'],
  template: '#card_template',
  methods: {
  	delete_me() {
      // good way - send event
    	this.$root.$emit('delete_me_event', this.param)
      // bad way - using closures
      //app.deleteCard(this.param);
    }
  },
});

class Card {
  constructor(text) {
    this.text = text;
  }
}

let cards = [
  new Card('card text 1'),
  new Card('card text 2'),
];

var app = new Vue({
    el: '#app' ,
    data: {
      cards_array: cards,
    },
    methods: {
        addCard: function () {
          this.cards_array.push(new Card('xxx'));
        },
        deleteCard: function (card) {
          //console.log(card);
          let index = this.cards_array.indexOf(card);
          if(index !== -1) {
            this.cards_array.splice(index, 1);
          }
        }
    },
    created() {
      this.$root.$on('delete_me_event', (card) => this.deleteCard(card));
    }
});