Vue.js Basics

Get started with Vue.js

HTML

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p v-if="hobbyWasDeleted" >Hobby deleted!</p>
  <p :class="{'more-than-three': hs.length > 3}">Hobbies: {{ hs.length }}</p>
  <input type="text" v-model="newHobbyName"/>
  <button @click="addNewHobby">Add new hobby</button>
  <ul>
  <!-- <li v-for="h in hs" :id="h.index" @click="deleteThisElement(h.index)">{{ h.value }}</li> -->
  
  <li v-for="h in hs" :id="h.index" @click="deleteThisElement(h.index)">
  <hobby :value="h"></hobby>
  </li>
  
  </ul>
</div>

CSS

.more-than-three {
  color: red
}

JavaScript

Vue.component('hobby', {
	props: [ 'value' ],
  template: '<p>{{ value.value }} </p>'
})

new Vue({
el: '#app',
data: {
	newHobbyName: "xxx",
  hobbyWasDeleted: false,
	hs: [
		{ index: 0, value: 'rockets' },
		{ index: 1, value: 'tennis' }
	]
},
methods: {
	addNewHobby : function() {
    this.hs.push({
      index: this.hs.length > 0 
      	? this.hs[this.hs.length-1].index + 1 
        : 0, 
      value: this.newHobbyName
      });
	},
  deleteThisElement(index) {
  	for(i=0; i < this.hs.length; ++i) {
    	if (this.hs[i].index == index) {
      	this.hs.splice(i, 1);
        this.hobbyWasDeleted = true
      	break;
      }
    }
  }
}
})