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

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.

主站蜘蛛池模板: 宁晋县| 东宁县| 凤翔县| 洪泽县| 江源县| 苗栗县| 昆明市| 福清市| 岚皋县| 博罗县| 义马市| 莫力| 张家界市| 兴国县| 同仁县| 武平县| 罗平县| 葵青区| 东台市| 桑植县| 米脂县| 探索| 汾西县| 寿宁县| 南昌市| 阿尔山市| 钟山县| 惠水县| 江川县| 黄龙县| 夏河县| 丰宁| 玛多县| 楚雄市| 玉树县| 凤翔县| 昌平区| 太保市| 临泽县| 连平县| 崇文区|