官术网_书友最值得收藏!

Using custom events to change the filter field

With custom events, you can pass data back up to the parent instances using the $on and $emit functions. For this app, we are going to store the filtering data on the parent Vue instance and update it from the component. The team-member component can then read the data from the Vue instance and filter accordingly.

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 <filtering> 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.

主站蜘蛛池模板: 宜宾县| 大城县| 牟定县| 江西省| 吴江市| 汉源县| 甘南县| 凤山县| 旬邑县| 铜山县| 石泉县| 安图县| 福安市| 喀什市| 唐山市| 莫力| 临颍县| 比如县| 安新县| 固始县| 湘潭县| 会宁县| 弋阳县| 昭苏县| 麻栗坡县| 芜湖市| 宁波市| 平潭县| 长宁区| 虹口区| 井冈山市| 锦州市| 库尔勒市| 凤庆县| 新兴县| 蚌埠市| 屯留县| 华亭县| 大港区| 息烽县| 金乡县|