在vue事件中,與之相關的兩個屬性是$emit、$on這個屬性,其中$emit是用來觸發當前實例上的事件的,$on是用來監聽當前實例上的自定義事件的,可以由$emit觸發,這一對屬性有點類似於觸發事件與事件處理程序分開這一原理,既可以傳播也可以方便監聽修改
$emit
Vue.component('magic-eight-ball', {
data: function () {
return {
possibleAdvice: ['Yes', 'No', 'Maybe']
}
},
methods: {
giveAdvice: function () {
var randomAdviceIndex = Math.floor(Math.random() * this.possibleAdvice.length)
this.$emit('give-advice', this.possibleAdvice[randomAdviceIndex])
}
},
template: `
<button v-on:click="giveAdvice">
Click me for advice
</button>
`
})
從以上可以看出,$emit有兩個參數(事件名,值),
Vue.component('welcome-button', {
template: `
<button v-on:click="$emit('welcome')">
Click me to be welcomed
</button>
`
})
只有一個事件名
$on
這個屬性就比較單一了,他有兩個參數(事件名或者參數值,回調函數)
vm.$on('test', function (msg) {
console.log(msg)
})
vm.$emit('test', 'hi')
// => "hi"