Monday, 17 July, 2017 UTC


Summary

Introduction to Vue ToDo List
In the earlier post about Creating a ToDo List, we learned about creating a ToDo list component along with the various ways in which we can create a Vue instance. We also learned about the root element which holds the entire application in place and how it’s composed of various other elements. Since the entire UI view is composed of various elements we can represent it in rather a tree structure where every individual part of the tree behaved as an independent component and has its own functions that one can deal with.
In today’s experiment, we will go ahead with adding a few functionalities to the Vue component which we created in the previous tutorial. In this present sample as well we will go ahead using JSFiddle for Vue. Hope you all remember the way in which we can set JSFiddle up or you can alternatively go to the article which we wrote on this particular topic “Getting Started with Vue using Fiddle“.
NOTE: If you are new to the blog and want to follow up from the beginning of the series. For all of you, we have an index being defined that will help you guys out for looking into each and every tutorial. you can go ahead and click this “Learn Everything about VueJS
Functions of Vue ToDo List
We are taking into consideration only a few Vue functions for this article. You guys can implement much more as we proceed with your level of understanding and whatever feature you require. This Vue ToDo list sample will contain the minimal functions to make the list work. So let’s get started with the same.

Create a ToDo Item

As mentioned already for the creation of the ToDo list as well as the Creation of the ToDo component I will recommend you all to have a look at the previous article. It has a detailed version of this particular operation and makes it pretty easy to get started. The link to the previous Tutorial is here.

Delete a ToDo Item

Deleting the ToDo list will follow this particular algorithm
  1. Modify the Component to accommodate the index value
  2. Creating an Event Bus Component for Global Communication
  3. Emit and Consume events from the Event Bus
  4. Define a delete function with argument as index
  5. User Clicks on the Delete Button
  6. On click of delete, a function is triggered which carries the index of the item in the list
  7. The function receives the index and deletes it from the Array
STEP 1
Let’s achieve this. We need to modify our ToDo component first in order to accommodate the index values. The component code will add a new property called
index
. The code can be seen below
Vue.component('list-item', {
  props: ['todo','index'],
  template: '<li class="list-group-item" :id="index">{{todo.text}}</li>'
})
As you can see in line number two we added an index as a new property to the component and this will take up the index of the current item that is being addressed from the array. In order to bind this to the attribute
id
, have a look at the syntax below. This is how you add values to the attributes.
:id="index"
STEP 2
Let’s create an Event Bus. In order to explain this let’s follow simple steps below
  1. When someone deletes the item the parent component should be aware
  2. This can be done using a simple child-parent communication
  3. But we are using a Global communication model where we will be using an Event Bus Component
  4. The Child will emit an event to the event Bus and the parent will listen for this event
  5. This will help us to communicate between child and parent
  6. Code for a simple Event Bus Component is below
    var EventBus = new Vue();
    
    // In order to emit an Event
    EventBus.$emit('nameOfEvent','value of event');
    
    // In order to consume an event and listen for it
    EventBus.$on('nameOfEvent',function(valueOfEvent){
    // Your implementation code.
    })
  7. The above code can be easily implemented in our scenario where we are going to create an event bus and then use it for Delete as well as Mark as Completed purpose. Now the HTML and JavaScript will look as follows:-
    <div id="app">
      <ol class="list-group">
        <list-item v-for="(item,index) in items" v-bind:todo="item" v-bind:index="index" v-bind:key="item.text">
        </list-item>
      </ol>
      <br>
      <input v-model="newItem" />
      <button v-on:click="addToList()">Add Item</button>
    </div>

    // Creating an EventBus
    var EventBus = new Vue();
    
    // ToDo list component
    Vue.component('list-item', {
      props: ['todo', 'index'],
      template: '<li class="list-group-item" :id="index">{{todo.text}}&nbsp;&nbsp;&nbsp;<button v-on:click="deleteItem(index)">Delete</button></li>',
      methods: {
        deleteItem: function(index) {
          EventBus.$emit('deletedindex', index)
        }
      }
    });
    
    // ROOT component
    var app7 = new Vue({
      el: '#app',
      data: {
        items: [{
          text: 'Buy some fruits'
        }, {
          text: 'Get home early'
        }],
        newItem: ''
      },
      created: function() {
        EventBus.$on('deletedindex', function(index) {
          console.log('Got Item with index : '+index)
        })
      },
      methods: {
        addToList: function() {
          this.items.push({
            text: this.newItem
          })
        }
      }
    });

    In the JavaScript, if you see the line number 26, it refers to the created event which is a lifecycle hook for Vue which we will be discussing on the Vue Lifecycle events. So now the Event bus is bound. Whenever someone clicks on the delete button the Event bus triggers an event with the event name, which is in this case 
    deletedindex
     with a value of the index. This is caught by the parent function, which on the creation of the component calls for an event listener which Triggers the Event Bus. Now let’s implement delete feature with the above understanding. Delete method is pretty simple which is being called by the Event Bus above when someone clicks on the delete button. The code is as follows. This is the modified ROOT element.
    // ROOT component
    var app7 = new Vue({
      el: '#app',
      data: {
        items: [{
          text: 'Buy some fruits'
        }, {
          text: 'Get home early'
        }],
        newItem: ''
      },
      created: function() {
      	var this_1 = this;
        EventBus.$on('deletedindex', function(index) {
          this_1.deleteItemfromList(index);
        })
      },
      methods: {
        addToList: function() {
          this.items.push({
            text: this.newItem
          });
          this.newItem='';
        },
        deleteItemfromList:function(index){
        	this.items.splice(index,1);
        }
      }
    });
This gives you a simple ToDo list where you can add and remove values using Global Event Bus. We will move ahead and see how it looks like when put in practice. The GIF of this is shown below and the code can be found in the JSFiddle.
  • Facebook
  • Twitter
  • Google+
  • LinkedIn
  • Buffer
Vue Global Event Bus
The code for the entire post can be found out here at JSFiddle. We have also posted the code below. Please have a look at the code below.
Conclusion
In the next article, we can use the above methods in order to get our app fully functional and have a feature where you can complete and archive the component. We will also try to narrow down the approach and get a video ready for the same.
The post Vue ToDo list with Delete Option & Global Event Bus – Part II appeared first on The Web Juice.