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

  • Vue.js 2.x by Example
  • Mike Street
  • 329字
  • 2021-07-02 20:00:32

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.

主站蜘蛛池模板: 东丽区| 壤塘县| 休宁县| 巴彦县| 五莲县| 曲阜市| 昌乐县| 于田县| 体育| 罗源县| 克拉玛依市| 岑溪市| 昌邑市| 五家渠市| 筠连县| 会宁县| 连江县| 永城市| 布拖县| 额敏县| 额尔古纳市| 梁河县| 延吉市| 都匀市| 益阳市| 湟源县| 七台河市| 罗定市| 青川县| 理塘县| 惠州市| 营山县| 安龙县| 宁蒗| 琼结县| 含山县| 呼玛县| 镇沅| 特克斯县| 武夷山市| 卢湾区|