1.安装依赖

npm install --save mitt 

2.在main.ts或者main.js同级目录下建立一个bus.js文件

import mitt from "mitt";
const bus = {};
const emitter = mitt();
bus.$on = emitter.on;
bus.$off = emitter.off;
bus.$emit = emitter.emit;

export default bus

3.在需要用bus.js的组件中引用

<template>
  <div class="Parent" ref="Parent">
    <el-button @click="EmitValue">EmitValue</el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted,reactive,provide,readonly,ref} from 'vue';
import bus from '@/bus'
export default defineComponent({
  name: 'Parent',
  components:{

  },
  setup(props,ctx){

  //绑定的方法,第三方传值(任何组件的传值)
  const EmitValue=()=>{
    bus.$emit("Deom","Deom")
  }
 
  })
  return{
    EmitValue
  }
  },
  props: {
  },
});
</script>

4.在接收消息的组件中引用

<template>
  <div class="Other">
    <p>{{name}}</p>
  </div>
</template>

<script lang="ts">
import { defineComponent,onMounted,reactive,inject,ref} from 'vue';
import bus from '@/bus'
export default defineComponent({
  name: 'Other',
  components:{
    
  },
  setup(props){
  const name = ref(null)
  bus.$on('wode', (data) => {
    name.value = data
    console.log(data)
  })
  
  onMounted(async () => {
    
  })
  return{
    name,
  }
  },
  props: {
  },
});
</script>
Logo

前往低代码交流专区

更多推荐