在Vue实例中,vm.$off
提供了灵活的方式来移除事件监听器。下面是如何使用 vm.$off
来移除特定条件下的事件监听的方法:
针对具体事件名称移除监听器:
// 假设已有一个名为 'myEvent' 的事件监听器被添加到 Vue 实例 vm 上
vm.$off('myEvent');
移除某个事件上的指定回调函数:
const myCallback = function () {
console.log('This will only be called once.');
};
// 添加一个具有明确引用的回调给事件 'custom'
vm.$on('custom', myCallback);
// 使用相同的回调引用来移除它
vm.$off('custom', myCallback);
移除所有类型的事件监听器:
// 这将清除该组件内所有的事件监听器
vm.$off();
为了防止不必要的内存占用并保证应用性能,在适当的时候如组件卸载前应当考虑清理不再使用的全局或局部事件监听。
vm.$emit
可以携带额外的参数,在触发事件的同时将这些参数传递给监听器回调函数。具体来说,可以在 vm.$emit
方法调用中添加任意数量的附加参数,这些参数会依次传入到相应的监听器回调函数之中。
示例如下:
new Vue({
data: {
message: 'Hello Vue!',
extraInfo: 'Additional Information'
},
created: function () {
// 使用 vm.$on 注册监听器并接收两个参数
this.$on('showMessage', function (msg, info) {
console.log(msg); // 输出:Hello Vue!
console.log(info); // 输出:Additional Information
});
},
methods: {
sendMessage: function () {
// 触发 'showMessage' 事件,并传递多个参数
this.$emit('showMessage', this.message, this.extraInfo);
}
}
});
当 sendMessage
方法被执行时,将会触发名为 'showMessage'
的事件并将两个参数一同发送出去。
Vue 实例的方法与事件允许开发者监听和触发自定义事件,这些功能有助于组件间的通信。
- 监听单次发生的自定义事件可以使用
vm.$once(event, callback)
。此方法仅当事件首次发生时执行回调函数,之后该监听器会被移除
vm.$once('custom-event', function () {
console.log('This will only trigger once.')
})
- 对于需要持续监听的事件,则应该采用
vm.$on(event, callback)
方法。通过这个方法注册的监听器会在每次指定事件被触发的时候运行所提供的回调函数
vm.$on('test', function (message) {
console.log(message)
})
// 触发 'test' 事件并传入参数
vm.$emit('test', 'hello world')
- 若要停止监听某个特定事件或者清除全部监听器,那么可借助
vm.$off()
来实现。不带参数调用将会关闭所有监听;只给出事件名称则会针对那个具体类型的监听做清理工作;若同时指定了事件名及其对应的处理器,则只会删除那一条绑定关系
// 移除名为 'test' 的所有监听者
vm.$off('test')
// 或者更精确地选择性取消
const myCallback = function (msg) { /* ... */ }
vm.$on('specificEvent', myCallback)
// 后续想要撤销上述操作
vm.$off('specificEvent', myCallback)
Instance Methods / Events
vm.$on( event, callback )
Arguments:
{string | Array<string>} event (array only supported in 2.2.0+)
{Function} callback
Usage:
Listen for a custom event on the current vm. Events can be triggered by vm.$emit. The callback will receive all the additional arguments passed into these event-triggering methods.
Example:
vm.$on('test', function (msg) {
console.log(msg)
})
vm.$emit('test', 'hi')
// => "hi"
vm.$once( event, callback )
Arguments:
{string} event
{Function} callback
Usage:
Listen for a custom event, but only once. The listener will be removed once it triggers for the first time.
vm.$off( [event, callback] )
Arguments:
{string | Array<string>} event (array only supported in 2.2.2+)
{Function} [callback]
Usage:
Remove custom event listener(s).
If no arguments are provided, remove all event listeners;
If only the event is provided, remove all listeners for that event;
If both event and callback are given, remove the listener for that specific callback only.
vm.$emit( eventName, […args] )
Arguments:
{string} eventName
[...args]
Trigger an event on the current instance. Any additional arguments will be passed into the listener’s callback function.
Examples:
Using $emit with only an event name:
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!')
}
}
})
Using $emit with additional arguments:
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>
})
new Vue({
el: ‘#emit-example-argument’,
methods: {
showAdvice: function (advice) {
alert(advice)
}
}
})