知微坚果的拾光小镇 知微坚果的拾光小镇
首页
随笔
  • Golang

    • 基础
    • 第三方库
  • 前端

    • Vue
    • Flutter
  • 开发工具
  • 系统工具
  • Timer (opens new window)
  • 时间线
  • 关于
GitHub (opens new window)

知微坚果

行者常至,为者常成
首页
随笔
  • Golang

    • 基础
    • 第三方库
  • 前端

    • Vue
    • Flutter
  • 开发工具
  • 系统工具
  • Timer (opens new window)
  • 时间线
  • 关于
GitHub (opens new window)
  • Vue3笔记之自定义指令

  • 前端
  • Vue3
知微坚果
2020-12-14
目录

Vue3笔记之自定义指令

# 概览

$on,$off 和 $once 实例方法已被移除,应用实例不再实现事件触发接口。

# 2.x 语法

在 2.x 中,Vue 实例可用于触发由事件触发 API 通过指令式方式添加的处理函数 ($on,$off 和 $once)。这可以创建 event hub,用来创建在整个应用程序中可用的全局事件监听器:

// eventHub.js

const eventHub = new Vue()

export default eventHub
1
2
3
// ChildComponent.vue
import eventHub from './eventHub'

export default {
  mounted() {
    // 添加 eventHub 监听器
    eventHub.$on('custom-event', () => {
      console.log('Custom event triggered!')
    })
  },
  beforeDestroy() {
    // 移除 eventHub 监听器
    eventHub.$off('custom-event')
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ParentComponent.vue
import eventHub from './eventHub'

export default {
  methods: {
    callGlobalCustomEvent() {
      eventHub.$emit('custom-event') // 当 ChildComponent 被挂载,控制台中将显示一条消息
    }
  }
}
1
2
3
4
5
6
7
8
9
10

# 3.x 更新

我们从实例中完全移除了 $on、$off 和 $once 方法。$emit 仍然包含于现有的 API 中,因为它用于触发由父组件声明式添加的事件处理函数。

# 迁移策略

可以使用实现了事件触发接口的外部库来替换现有的 event hub,例如 mitt 或 tiny-emitter。

兼容性构建中也支持这些方法。

最好我们选择其他方式实现吧。

#Vue#Vue3
更新时间: 12/2/2022, 12:38:29 AM
最近更新
01
SpringBoot3.0快速上手
12-07
02
Spring事务管理源码分析
12-06
03
Golang工程结构最佳实践
12-04
更多文章>
Theme by Vdoing | Copyright © 2022-2022 知微坚果 | 拾光小镇
蜀ICP备17001150号-2
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式