安装:npm i mitt -s
点击按钮,改变兄弟组件的值
1.父组件
<template>
<div>
<brotherC></brotherC>
<brotherD></brotherD>
</div>
</template>
<script>
import brotherC from "@/components/brother/brotherC";
import brotherD from "@/components/brother/brotherD";
export default {
name: "brotherLink",
components: {
brotherC,
brotherD,
},
}
</script>
2.子组件1
<template>
<div>
<h2>brotherC</h2>
<a-button @click="changeMsg" type="primary">点击修改msg</a-button>
</div>
</template>
<script>
import { reactive, ref } from "vue";
import emitter from "@/common/js/utils/mitt.js";
export default {
name: "brotherC",
setup() {
let changeMsg = () => {
emitter.emit('change-msg')
};
return {
changeMsg,
};
},
};
</script>
<style lang='scss' scoped>
</style>
3.子组件2
<template>
<div>
<h2>brotherD</h2>
<p>{{ msg }}</p>
</div>
</template>
<script>
import { reactive, ref, onUnmounted } from "vue";
import emitter from "@/common/js/utils/mitt.js"
export default {
name: "brotherD",
setup() {
let msg = ref("hello");
let changeMsg = ()=>{
msg.value = '我被改变啦';
}
// 监听事件,更新数据
emitter.on('change-msg',changeMsg)
// 卸载
onUnmounted(()=>{
console.log('onUnmounted')
emitter.off('change-msg',changeMsg)
})
return {
msg,
changeMsg
};
},
};
</script>
<style lang='scss' scoped>
</style>
4.mitt.js
import mitt from 'mitt';
const emitter = mitt();
export default emitter;