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

The first step is to utilize the filter object on the parent Vue instance. Remove the data


object from your component and pass in the parent one via a prop - just as we did with the


team-member component:


<filtering v-bind:filter="filter"></filtering>

We are now going to modify the changeFilter function to emit the event data so the


parent instance, so it can update the filter object.


Remove the existing changeFilter method from the filtering component and create a


new one called change-filter-field. Within this method, we just need to $emit the


name of the field selected in the drop-down menu. The $emit function takes two


parameters: a key and the value. Emit a key of change-filter-field and pass the


event.target.value as the data. When using variables with multiple words (For


example, changeFilterField), ensure these are hyphenated for the event name (the first


parameter of the $emit function) and the HTML attribute:


changeFilterField(event) {
this.$emit('change-filter-field',
event.target.value);
}

In order to then pass the data to the changeFilter method on our parent Vue instance, we
need to add a new prop to our element. This uses v-on and binds to the


custom event name. It then has the parent method name as the attribute value. Add the
attribute to your element:


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

This attribute preceding tells Vue to trigger the changeFilter method when a change-


filter-field event is emitted. We can then tweak our method to accept the parameter as


the value:


changeFilter(field) {
this.filter.query = '';
this.filter.field = field;
}

This then clears the filters and updates the field value, which then ripples down to our
components via props.

Free download pdf