可實(shí)現(xiàn)組件之間的通信,主要講父子組件之間系忙。
以自定義一個(gè)t-search組件為例。
<temple>
<div>
<p>{{ value }}</p>
<t-search @search="search"
/** 方式一實(shí)現(xiàn)value值動(dòng)態(tài)更新 */
@input="input"
/** 方式二實(shí)現(xiàn)value值動(dòng)態(tài)更新( 方式一的官方封裝 ) */
v-modle='value'
></t-search>
</div>
</temple>
<script>
import Vue from 'vue';
const TSearch = Vue.extend({
temple: '<div> <input type="text" :value="value" @input="sendValue" @keyup.enter="sendSearchValue"></input> </div>',
props: ['value'],
methods: {
sendValue(e) {
this.emit('input', e.target.value);
},
sendSearchValue(e) {
this.emit('search', e.target.value);
}
}
});
export default Vue.extend({
data() {
return {
value: 'default'
}
},
methods() {
search(val) {
alert(val);
},
input(val) {
this.value = val;
}
},
components: {
TSearch
}
})
<script>
summary
publish / subscribe 模式; $emit 發(fā)布事件以及傳遞參數(shù) 父組件訂閱事件后做出相關(guān)反應(yīng)缨恒;