Vue.js Basics

Get started with Vue.js

by Mingtao Sun

HTML

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

<div id="app">
  <p v-bind:class="{ 'less-hobby': hobbies.length<3, 'more-hobby': hobbies.length>=3}">Hobbies: {{hobbies.length}}</p>
  <ul>
    <hobby-item v-for="hobby in hobbies" v-bind:hobby="hobby" v-on:removehby="removeHobby($event)"></hobby-item>  
  </ul>
  <input v-model="newHobby"/>  
  <button v-on:click="addNewHobby">New Hobby</button><br/>
  <p v-if="hobbyDeleted">Hobby deleted</p>
</div> 
<!-- 
  1) Create a <div> and take control with a Vue Instance
  2) Output an array of hobbies in this <div> (provide some default hobbies)
  3) Add a 'New Hobby' button + <input> field where you add the hobby the user entered to the list
  4) Make the hobbies clickable to remove them once clicked
  5) Add a <p>Hobby deleted!</p> which is only shown once at least one hobby was deleted (be creative on how to track this!)
  6) Add a hobby counter (<p>Hobbies: ...</p>) above the list of hobbies
  7) Dynamically style/ add <class></class>es to the hobby counter, depending on whether you have more or less than 3 hobbies
  8) Outsource your hobbies (the <li> elements) into a re-usable component
-->

CSS

.less-hobby {
  background-color: blue;  
}
.more-hobby {
  background-color: yellow;
}

JavaScript

Vue.component('hobby-item', {
	props: ['hobby'],
  template: '<li v-on:click="removehobby(hobby)">{{hobby}}</li>',
  methods: {
  	removehobby: function(hb){
    	this.$emit('removehby', hb);
    }
  },
})


new Vue({
	el: "#app",
  data: {
  	hobbies : ['book', 'movie', 'fishing'],
    newHobby: '',
    hobbyDeleted: false
  },
  methods: {
  	addNewHobby: function(){
    	this.hobbies.push(this.newHobby);
    },
    removeHobby: function(hobby){
    	for (var i=0; i<this.hobbies.length; i++){
      	if (this.hobbies[i] == hobby){
        	this.hobbies.splice(i, 1);
          this.hobbyDeleted = true;
          break;
        }
      }
    }
  }
});