Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Optimizing your App and Using Components to Display Data Chapter 3

Updating the filter query


To emit the query field, we are going to use a new Vue key that we have not used before,
called watch. The watch function tracks a data property and can run methods based on the


output. The other thing it is able to do is to emit events. As both, our text field and radio
buttons are set to update the field.query variable, we will create a new watch function on


this.


Create a new watch object after the methods on your component:


watch: {
'filter.query': function() {
}
}

The key is the variable you wish to watch. As ours contains a dot, it needs to be wrapped in


quotes. Within this function, create a new $emit event of change-filter-query that


outputs the value of filter.query:


watch: {
'filter.query': function() {
this.$emit('change-filter-query',
this.filter.query)
}
}

We now need to bind this method and custom event to the component in the view, so it is


able to pass the data to the parent instance. Set the value of the attribute


to changeQuery—we'll make a method to handle this:


<filtering v-bind:filter="filter" v-on:change-
filter-field="changeFilter" v-on:change-filter-
query="changeQuery"></filtering>

On the parent Vue instance, make a new method, titled changeQuery, that simply updates


the filter.query value based on the input:


changeQuery(query) {
this.filter.query = query;
}

Our filtering is now working again. Both updating the select box and the input box (or


radio buttons) will now update our person list. Our Vue instance is significantly smaller


and our templates and methods are contained with separate components.

Free download pdf