實例方法 / 事件
vm.$on
監聽當前實例上的自定義事件。事件可以由 vm.$emit 觸發。回調函數會接收所有傳入事件觸發函數的額外參數。
vm.$on('test', function (msg) {console.log(msg)
})
vm.$emit('test', 'hi')
// => "hi"
vm.$once( event, callback )
監聽一個自定義事件,但是只觸發一次。一旦觸發之后,監聽器就會被移除。
vm.$off
移除自定義事件監聽器。
如果沒有提供參數,則移除所有的事件監聽器;
如果只提供了事件,則移除該事件所有的監聽器;
如果同時提供了事件與回調,則只移除這個回調的監聽器。
vm.$emit
觸發當前實例上的事件。附加參數都會傳給監聽器回調。
Vue.component('welcome-button', {template: `<button v-on:click="$emit('welcome')">Click me to be welcomed</button>`
})
<div id="emit-example-simple"><welcome-button v-on:welcome="sayHi"></welcome-button>
</div>
new Vue({el: '#emit-example-simple',methods: {sayHi: function () {alert('Hi!')}}
})
配合額外的參數使用 $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>`
})
<div id="emit-example-argument"><magic-eight-ball v-on:give-advice="showAdvice"></magic-eight-ball>
</div>
new Vue({el: '#emit-example-argument',methods: {showAdvice: function (advice) {alert(advice)}}
})