非父子組件傳值(同級組件傳值)

1、公共bus.js

import Vue from 'vue';

// 使用 Event Bus
const bus = new Vue();

export default bus;

2、組件1

<template>
  <div>
    A組件:
    <span>{{elementValue}}</span>
    <input type="button" value="點擊觸發" @click="elementByValue">
  </div>
</template>
<script>
  // 引入公共的bug,來做爲中間傳達的工具
  import Bus from './bus.js'
  export default {
    data () {
      return {
        elementValue: 4
      }
    },
    methods: {
      elementByValue: function () {
        Bus.$emit('val', this.elementValue)
      }
    }
  }
</script>

3、組件2 

 

<template>
  <div>
    B組件:
    <input type="button" value="點擊觸發" @click="getData">
    <span>{{name}}</span>
  </div>
</template>
<script>
  import Bus from './bus.js'
  export default {
    data () {
      return {
        name: 0
      }
    },
    mounted: function () {
      var vm = this
      // 用$on事件來接收參數
      Bus.$on('val', (data) => {
        console.log(data)
        vm.name = data
      })
    },
    methods: {
      getData: function () {
        this.name++
      }
    }
  }
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章