vue1.0中 vm.$dispatch 和 vm.$broadcast 被棄用,改用$emit,$on
vm.$on( event, callback )
監(jiān)聽(tīng)當(dāng)前實(shí)例上的自定義事件。事件可以由vm.$emit觸發(fā)。回調(diào)函數(shù)會(huì)接收所有傳入事件觸發(fā)函數(shù)的額外參數(shù)。
vm.$emit( event, […args] )
觸發(fā)當(dāng)前實(shí)例上的事件。附加參數(shù)都會(huì)傳給監(jiān)聽(tīng)器回調(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)寫,監(jiān)聽(tīng)由子組件vm.$emit觸發(fā)的事件,通過(guò)onSelectType()接受從子組件傳遞過(guò)來(lái)的數(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>子組件通過(guò)$emit來(lái)觸發(fā)事件,將參數(shù)傳遞出去。
以上所述是小編給大家介紹的vue2.0 中#$emit,$on的使用詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)錯(cuò)新站長(zhǎng)站網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選