vue中bus的使用

新建一个bus.js文件,并在main.js引入并全局使用它

import Vue from 'vue'

const bus = new Vue({
  data: {
    number: 1
  }
})

export default {
  install() {
    Object.defineProperty(Vue.prototype, '$bus', {
      value: bus
    });
  }
}

 

bus.vue组件

<template>
  <div class="sdktest">
    <ul>
      <li class="sdktest-item" @click="addNum">父组件派发事件----点击增加bus(number)------{{ $bus.number }}</li>
      <bus-child></bus-child>
    </ul>
  </div>
</template>

<script>
  import BusChild from './components/bus-child'
  export default {
    name: "index",
    components: {
      BusChild
    },
    methods: {
      addNum() {
        this.$bus.$emit('addNum',this.$bus.number++);
      }
    }
  }
</script>

<style scoped>
  .sdktest {
    overflow: hidden;
    background-color: #fff;
    font-size: 36px;
  }
  .sdktest-item {
    width: 560px;
    /*height: 80px;*/
    margin: 40px auto;
    border: 1px solid #eee;
    border-radius: 10px;
    background-color: #3ec7e7;
    color: #fff;
    text-align: center;
    line-height: 80px;
  }
  .sdktest-item:nth-child(2n) {
    background-color: #42cd56;
  }
</style>

 

bus-child组件

<template>
  <div class="sdktest">
    <ul>
      <li class="sdktest-item">子组件监听事件---number:{{ $bus.number}}</li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: "bus-child",
    mounted() {
      this.$bus.$on('addNum',(payload) => {
        console.log(payload);
      });
    }
  }
</script>

<style scoped>
  .sdktest {
    overflow: hidden;
    background-color: #fff;
    font-size: 36px;
  }
  .sdktest-item {
    width: 560px;
    height: 80px;
    margin: 40px auto;
    border: 1px solid #eee;
    border-radius: 10px;
    background-color: #3ec7e7;
    color: #fff;
    text-align: center;
    line-height: 80px;
  }
  .sdktest-item:nth-child(2n) {
    background-color: #42cd56;
  }
</style>

 

页面展示

vue中bus的使用

上一篇:The I2C-bus specification(V2.1)摘要


下一篇:vue组件通讯---$bus