Vue之组件之事件总线
- 创建新项目
G:\myvue>vue create vcbus 选择第二项。 - 开启事件总线
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
beforeCreate() {
Vue.prototype.$bus=this;
},
render: h => h(App),
}).$mount('#app')
在项目生成的main.js里添加代码
beforeCreate() {
Vue.prototype.$bus=this;
},
3.新建两个组件VcA,VcB
VcA
<template>
<div class="vca">
<h2>VcA</h2>
<button @click="sendMessage">sendMessage</button>
</div>
</template>
<script>
export default {
name: "VcA",
methods:{
sendMessage(){
this.$bus.$emit("acceptMessage","I love life")
}
}
}
</script>
<style scoped>
.vca{
width:50%;
border-color: blue;
border-style: double;
background-color: cadetblue;
}
</style>
VcB
<template>
<div CLASS="vcb">
<h1>VcB</h1>
<h1>{{message}}</h1>
</div>
</template>
<script>
export default {
name: "VcB",
data(){
return{
message:''
}
},
methods:{
acceptMessage(msg){
this.message=msg;
}
},
mounted() {
this.$bus.$on("acceptMessage",this.acceptMessage)
},
beforeDestroy() {
this.$bus.$off("acceptMessage")
}
}
</script>
<style scoped>
.vcb{
width:50%;
border-style: double;
border-color: brown;
background-color: darkgrey;
}
</style>
App
<template>
<div id="app">
<VcA></VcA>
<VcB></VcB>
</div>
</template>
<script>
import VcA from "./components/VcA";
import VcB from "@/components/VcB";
export default {
name: 'App',
components: {
VcB,
VcA,
}
}
</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>
4. 运行效果
5. 总结 A传消息到B 在A内用 this.
b
u
s
.
bus.
bus.emit(“acceptMessage”,“I love life”) 在B内用 mounted() { this.
b
u
s
.
bus.
bus.on(“acceptMessage”,this.acceptMessage) },接收 发布的接收的是this.KaTeX parse error: Expected '}', got 'EOF' at end of input: …y() { this.bus.$off(“acceptMessage”) }
|