当前位置:首页 > VUE

简单实现vue事件机制

2026-02-21 11:42:35VUE

Vue 事件机制实现

Vue 的事件机制主要基于发布-订阅模式,可以通过自定义实现一个简化版的事件系统。

核心概念

  1. 事件中心(Event Hub):管理所有事件的订阅和发布
  2. $on 方法:订阅事件
  3. $emit 方法:触发事件
  4. $off 方法:取消订阅

基础实现代码

class EventEmitter {
  constructor() {
    this.events = {}
  }

  $on(eventName, callback) {
    if (!this.events[eventName]) {
      this.events[eventName] = []
    }
    this.events[eventName].push(callback)
  }

  $emit(eventName, ...args) {
    const callbacks = this.events[eventName]
    if (callbacks) {
      callbacks.forEach(cb => cb(...args))
    }
  }

  $off(eventName, callback) {
    const callbacks = this.events[eventName]
    if (callbacks) {
      if (callback) {
        this.events[eventName] = callbacks.filter(cb => cb !== callback)
      } else {
        delete this.events[eventName]
      }
    }
  }
}

在 Vue 实例中集成

function initEvents(vm) {
  vm._events = Object.create(null)

  vm.$on = function(event, fn) {
    (vm._events[event] || (vm._events[event] = [])).push(fn)
    return vm
  }

  vm.$once = function(event, fn) {
    function on() {
      vm.$off(event, on)
      fn.apply(vm, arguments)
    }
    vm.$on(event, on)
    return vm
  }

  vm.$off = function(event, fn) {
    if (!arguments.length) {
      vm._events = Object.create(null)
      return vm
    }

    const cbs = vm._events[event]
    if (!cbs) return vm

    if (!fn) {
      vm._events[event] = null
      return vm
    }

    vm._events[event] = cbs.filter(cb => cb !== fn)
    return vm
  }

  vm.$emit = function(event) {
    const cbs = vm._events[event]
    if (cbs) {
      const args = Array.prototype.slice.call(arguments, 1)
      cbs.forEach(cb => cb.apply(vm, args))
    }
    return vm
  }
}

父子组件通信实现

// 父组件
const parent = new Vue()
parent.$on('child-event', (msg) => {
  console.log('收到子组件消息:', msg)
})

// 子组件
const child = new Vue()
child.$emit('child-event', 'Hello from child')

全局事件总线

Vue.prototype.$bus = new Vue()

// 组件A
this.$bus.$on('some-event', (data) => {
  console.log(data)
})

// 组件B
this.$bus.$emit('some-event', 'message')

注意事项

  1. 事件名称最好使用kebab-case命名规范
  2. 及时在组件销毁时移除事件监听
  3. 避免滥用全局事件总线,优先考虑props和自定义事件
  4. 复杂场景考虑使用Vuex状态管理

这种实现方式模拟了Vue核心的事件系统原理,实际Vue源码中事件处理更加复杂,包含更多边界情况处理。

简单实现vue事件机制

标签: 机制事件
分享给朋友:

相关文章

vue 实现hover事件

vue 实现hover事件

在Vue中实现hover事件可以通过多种方式完成,以下是常见的几种方法: 使用@mouseenter和@mouseleave指令 Vue提供了原生的事件监听指令,可以直接在模板中绑定鼠标进入和离开的…

jquery添加事件

jquery添加事件

jQuery 添加事件的方法 jQuery 提供了多种方法来为元素添加事件监听。以下是一些常用的方式: 使用 .on() 方法 .on() 是 jQuery 中推荐的事件绑定方法,支持直接绑定和委…

vue路由实现机制

vue路由实现机制

Vue 路由实现机制 Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。其核心机制包括路由匹配、导航守卫、动态路由等。 路由匹配 Vue Router 通过路…

vue实现事件捕获

vue实现事件捕获

Vue 中实现事件捕获的方法 在 Vue 中,默认情况下事件是通过冒泡机制传递的。如果需要实现事件捕获,可以通过以下方式: 使用 .capture 修饰符 Vue 提供了 .capture 事件修…

vue事件如何实现

vue事件如何实现

Vue 事件实现方法 Vue 中事件通过 v-on 指令或 @ 简写实现,支持原生 DOM 事件和自定义事件。 原生 DOM 事件绑定 <button v-on:click="handleCl…

vue实现全选事件

vue实现全选事件

Vue 实现全选事件 在 Vue 中实现全选功能通常涉及以下关键步骤: 数据绑定与状态管理 使用 v-model 绑定复选框的状态,确保数据与视图同步。通常需要一个数组存储选中项和一个布尔值控制全选…