首先得在mian.js中创建如下代码
在 Vue 实例的 beforeCreate 生命周期钩子中,将当前 Vue 实例赋值给 $bus
beforeCreate(){
Vue.prototype.$bus = this;
}
整体代码如下
new Vue({
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus = this;
}
}).$mount('#app')
我们APP.vue组件中创建如下代码
在组件的 mounted 生命周期钩子中,向全局事件总线监听 wasteMoney 事件。当 wasteMoney 事件被触发时,会执行事件处理器函数,从 this.money 中减去传递过来的 money 金额。
mounted(){
this.$bus.$on('wasteMoney',(money)=>{
this.money = this.money - money;
})
}
整体代码如下
<template>
<div id="app">
<h2>小明的爸爸现状有{{money}}元</h2>
<childComp></childComp>
</div>
</template>
<script>
import childComp from './components/childComp.vue'
export default {
name: 'App',
components: {
childComp
},
data() {
return {
money:1000
}
},
mounted(){
this.$bus.$on('wasteMoney',(money)=>{
this.money = this.money - money;
})
}
}
</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>
然后在其子组件内
通过全局事件总线触发 wasteMoney 事件,并传递事件参数 100。
wastMoney(){
this.$bus.$emit('wasteMoney',100)
}
整体代码如下
<template>
<div>小明要花钱了
<button @click="wastMoney">-100</button>
</div>
</template>
<script>
export default {
methods:{
wastMoney(){
this.$bus.$emit('wasteMoney',100)
}
}
}
</script>