- 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.
- Java多線程編程實戰(zhàn)指南:設計模式篇(第2版)
- Instant Testing with CasperJS
- GeoServer Cookbook
- 大學計算機基礎實驗教程
- Java虛擬機字節(jié)碼:從入門到實戰(zhàn)
- 正則表達式經典實例(第2版)
- Java:High-Performance Apps with Java 9
- Visual Foxpro 9.0數據庫程序設計教程
- Mastering Akka
- App Inventor創(chuàng)意趣味編程進階
- Vue.js光速入門及企業(yè)項目開發(fā)實戰(zhàn)
- Java程序設計教程
- Java程序設計實用教程(第2版)
- Raspberry Pi Robotic Projects
- WCF編程(第2版)