vue1.0中 vm.$dispatch 和 vm.$broadcast 被棄用,改用$emit,$on
vm.$on( event, callback )
監(jiān)聽當(dāng)前實例上的自定義事件。事件可以由vm.$emit觸發(fā)。回調(diào)函數(shù)會接收所有傳入事件觸發(fā)函數(shù)的額外參數(shù)。
vm.$emit( event, […args] )
觸發(fā)當(dāng)前實例上的事件。附加參數(shù)都會傳給監(jiān)聽器回調(diào)。
例子:
//父組件<template> <ratingselect @select-type="onSelectType"></ratingselect></template><script> data () { return { selectType: 0, }, methods: { onSelectType (type) { this.selectType = type } }</script>父組件使用@select-type="onSelectType"@就是v-on的簡寫,監(jiān)聽由子組件vm.$emit觸發(fā)的事件,通過onSelectType()接受從子組件傳遞過來的數(shù)據(jù),通知父組件數(shù)據(jù)改變了。
// 子組件<template> <div> <span @click="select(0, $event)" :class="{'active': selectType===0}"></span> <span @click="select(1, $event)" :class="{'active': selectType===1}"></span> <span @click="select(2, $event)" :class="{'active': selectType===2}"></span> </div></template><script> data () { return { selectType: 0, }, methods: { select (type, event) { this.selectType = type this.$emit('select-type', type) } }</script>子組件通過$emit來觸發(fā)事件,將參數(shù)傳遞出去。
以上所述是小編給大家介紹的vue2.0 中#$emit,$on的使用詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點
疑難解答