学习全局事件总线,非常非常好了解的简单小案例1

首先得在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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值