Vue3全局通信

229 阅读1分钟

前言

Vue的通信方式有很多种,但并不是每一种我们都会用到,经常用到的无非就是父子组件的通信和多层级间的父子通信。

mitt

在vue2中我们采用vue本身的监听属性来进行事件的全局通信,在3中我们采用mitt插件来完成事件的全局通信

1. 下载和安装mitt

在终端中输入以下命令行:

npm install mitt

2.导出事件总线

在src下创建bus.js

如下所示:

import mitt from "mitt";

export const $bus = mitt();

3.src中的components文件夹下创建父子文件parent和child

parent.vue

<template>
<div style="border: 1px solid black">
  <div>父级组件中的页面</div>
  <Child></Child>
  <button @click="send1">点击触发</button>
</div>
</template>

<script setup>
import Child from './Child';

// components: { Child }
const send1 = () => {
  console.log('发送事件开始')

}

</script>

<style scoped>

</style>

child.vue

<template>
  <div style="border: 1px solid red">
    <div>这是子级页面</div>
    <button @click="send2">发送</button>
  </div>
</template>

<script setup>
import {$bus} from "@/bus";
import { onMounted } from "vue";

const send2 = (res) => {
   console.log('111',res)
 }
 onMounted(()=>{
   $bus.on('name1',send2)
 })
</script>

<style scoped>

</style>

APP·VUE如下:

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <button @click="send">今天是周一</button>
  <HelloWorld msg="Welcome to Your Vue.js App" v-if="false"/>
  <Parent></Parent>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import Parent  from './components/parent'
import { $bus } from "@/bus";

export default {
  name: 'App',
  components: {
    HelloWorld,
    Parent
  },
  methods:{
    send(){
      console.log('我本将心向明月')
      $bus.emit('name1','朱小明的一天')
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

运行结果如下:

点击“今天是周一”,打印结果如下:

image.png

可以看出事件总线已经通知到了child。