Vue2-$on、$once、$off、$emit

341 阅读1分钟

$on 方法用于监听一个事件,并将对应的回调函数添加到事件队列 vm._events={eventName: []} 中。如果事件队列中不存在该事件,则会创建一个新的事件队列。

语法:$on(event: string | Array<string>, callback: Function)(只在 2.2.2+ 支持数组)

  • 绑定事件:$on('e1', callback)
  • 绑定多个事件:$on(['e1', 'e2'], callback)

$once 方法用于监听一个事件,但是只会在事件第一次被触发时执行回调函数,之后会自动移除该事件监听器。

语法: $once(event: string, callback: Function)

  • 绑定事件:$once('e1', callback)

$off 方法用于移除事件监听,可以根据传入的参数来进行不同的操作,包括移除所有事件、移除特定事件,以及移除特定事件的特定回调函数。

语法: $off(event?: string | Array<string>, fn?: Function) (只在 2.2.2+ 支持数组)

  • 移除所有事件:$off()
  • 移除指定事件:$off('e1')
  • 移除指定事件的特定回调:$off('e1', callback)
  • 移除多个事件:$off(['e1', 'e2'])
  • 移除多个事件的特定回调:$off(['e1', 'e2'], callback)

$emit 方法用于触发一个事件,并且可以传递参数给事件监听器。

语法: $emit(event: string, [...args])

  • 触发事件:$emit('eventName')
  • 触发事件并携带参数:$emit('eventName', arg1, arg2)

示例一: $on / $off / $emit

<template>
  <div>
    <button @click="bindEvent">$on 绑定事件</button>
    <button @click="unbindEvent">$off 解绑事件</button>
    <button @click="triggerEvent('事件参数')">$emit 触发事件</button>
  </div>
</template>

<script>
export default {
  methods: {
    bindEvent() {
      this.$on("custom-event", this.handleCustomEvent);
      console.log("绑定自定义事件 custom-event");
    },
    unbindEvent() {
      this.$off("custom-event", this.handleCustomEvent);
      console.log("解绑自定义事件 custom-event");
    },
    handleCustomEvent(param) {
      console.log("自定义事件 custom-event 触发了,参数值为:", param);
    },
    triggerEvent(param) {
      this.$emit("custom-event", param);
      console.log("触发自定义事件 custom-event,参数值为:", param);
    },
  },
};
</script>

示例二:$once / $emit

<template>
  <div>
    <button @click="bindEventOnce">$once 绑定事件</button>
    <button @click="triggerEventOnce('事件参数')">$emit 触发事件</button>
  </div>
</template>

<script>
export default {
  methods: {
    bindEventOnce() {
      this.$once("custom-event-once", this.handleCustomEventOnce);
      console.log("绑定自定义事件 custom-event-once");
    },
    handleCustomEventOnce(param) {
      console.log("自定义事件 custom-event-once 触发了,参数值为:", param);
    },
    triggerEventOnce(param) {
      this.$emit("custom-event-once", param);
      console.log("触发自定义事件 custom-event-once,参数值为:", param);
    },
  },
};
</script>