【Vue3】使用mitt实现任意组件通信
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
·
历史小剧场
最幸福的,就是中间那拨人,主要工作,叫做欺上瞒下,具体特点是,除了好事,什么都办;除了脸,什么都要。----《明朝那些事儿》
安装
npm install mitt
常用API
- mitt().on() 绑定事件
- mitt().emit() 触发事件
- mitt().off() 卸载某个事件
- mitt().all.clear() 卸载全部事件
使用方式一:封装模块暴露
步骤一
封装到utils工具箱中,对外暴露一个mitt实例
import mitt from 'mitt'
const emitter = mitt()
export default emitter;
步骤二
有两个组件,Child1,Child2
<!-- -->
<template>
<div>
<h3>子组件1</h3>
<h4>玩具: {{ toy }}</h4>
<button @click="sendToy">发送玩具</button>
</div>
</template>
<script lang="ts">
import { ref } from 'vue';
import mitter from '../../utils/emitter'
export default {
setup() {
const toy = ref("奥特曼")
const sendToy = () => {
mitter.emit('send-toy', toy)
}
return {
toy,
sendToy
}
}
}
</script>
<style lang="scss" scoped>
</style>
<!-- -->
<template>
<div>
<h3>子组件2</h3>
<h4>小孩: {{ boy }}</h4>
<h5>从子组件1来的玩具: {{ toy }}</h5>
</div>
</template>
<script setup lang="ts" name="Child2">
import { Ref, onUnmounted, ref } from 'vue';
import mitter from '../../utils/emitter'
const boy = ref('大傻叉')
const toy = ref()
mitter.on('send-toy', (val: Ref) => {
console.log("val => ", val)
toy.value = val.value
})
onUnmounted(() => {
mitter.all.clear()
})
</script>
<style lang="scss" scoped>
</style>
使用方式二:main.ts 挂载到全局
步骤一
main.ts
import mitt from 'mitt';
const app = createApp(App)
// 挂载到全局实例上
app.config.globalProperties.$EventBus = mitt()
步骤二
Child1:
<!-- -->
<template>
<div>
<h3>子组件1</h3>
<h4>玩具: {{ toy }}</h4>
<button @click="sendToy">发送玩具</button>
</div>
</template>
<script lang="ts">
import { getCurrentInstance, ref } from 'vue';
export default {
setup() {
const toy = ref("奥特曼")
// 同 vue2中的 this
const { proxy } = getCurrentInstance();
const sendToy = () => {
proxy.$EventBus.emit('send-toy', toy)
}
return {
toy,
sendToy
}
}
}
</script>
<style lang="scss" scoped>
</style>
Child2:
<!-- -->
<template>
<div>
<h3>子组件2</h3>
<h4>小孩: {{ boy }}</h4>
<h5>从子组件1来的玩具: {{ toy }}</h5>
</div>
</template>
<script setup lang="ts" name="Child2">
import { Ref, getCurrentInstance, onUnmounted, ref } from 'vue';
const { proxy } = getCurrentInstance();
const boy = ref('大傻叉')
const toy = ref()
proxy.$EventBus.on('send-toy', (val: Ref) => {
console.log("val => ", val)
toy.value = val.value
})
onUnmounted(() => {
proxy.$EventBus.all.clear()
})
</script>
<style lang="scss" scoped>
</style>
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:3 个月前 )
9e887079
[skip ci] 1 年前
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐




所有评论(0)