Vue2中:
new一个新的vue实例,用on和emit来对事件进行传输
main.js
import Vue from 'vue'
import App from './App.vue'
// 定义中央事件总线
const EventBus = new Vue()
Vue.config.productionTip = false
Vue.prototype.$EventBus = EventBus
new Vue({
render: h => h(App),
}).$mount('#app')
A组件:
<template>
<div class="hello">
<p>this is A component</p>
<input type="text" v-model="mymessage" @input="passData(mymessage)">
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
data() {
return {
mymessage: 'hello brother1'
}
},
methods: {
passData(val) {
// 触发全局事件globalEvent
this.$EventBus.$emit('globalEvent', val)
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
B组件:
<template>
<div class="so">
<p>this is B component</p>
<p>组件 A 传递过来的数据:{{ brothermessage }}</p>
</div>
</template>
<script>
export default {
name: "todo-item",
data() {
return {
mymessage: 'hello brother2',
brothermessage: ''
}
},
mounted() {
// 绑定全局事件globalEvent
this.$EventBus.$on('globalEvent', (val) => {
this.brothermessage = val
})
}
}
</script>
<style scoped>
</style>
Vue3中:
vue3中移除了 $on、$off和$once方法,所以我们如果希望继续使用全局事件总线,要通过第三方的库:
Vue3官方有推荐一些库,例如 mitt
安装mitt
npm install mitt
封装eventBus.js
import mitt from 'mitt'
const mitter = mitt()
export default emitter
在需要使用的组件中导入
A组件:
<template>
<div class="hello">
<p>This is A component</p>
<input type="text" v-model="inputValue" @input="passData(inputValue)">
</div>
</template>
<script>
import { ref } from 'vue'
import emitter from '@/utils/eventBus';
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<script setup>
const inputValue = ref("")
const passData = (val) => {
emitter.emit("globalEvent", val)
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
B组件:
<template>
<div class="so">
<p>This is B component</p>
<p>这里是B组件:{{ msg }}</p>
</div>
</template>
<script>
import { ref } from 'vue'
import emitter from '@/utils/eventBus';
export default {
name: "todo-item",
}
</script>
<script setup>
const msg = ref("")
emitter.on("globalEvent", (val) => {
msg.value = val
})
</script>
<style scoped>
</style>
触发事件
emitter.on("globalEvent", "测试1234")
监听事件
emitter.on("globalEvent", (info) => {
console.log("触发了当前的globalEvent")
})
指定监听移除
function removeEvent() {}
emitter.off("globalEvent", removeEvent)
移除所有监听
emitter.all.clear()