vue非父子傳值 創建公共文件bus.js

在這裏插入圖片描述

<template>
  <div>
      <h1>app</h1>
      <one></one>
      <two></two>
  </div>
</template>

<script>
import one from "./one.vue"
import two from "./two.vue"
export default {
    components:{
        one,
        two
    }
}
</script>

<style>

</style>
<template>
  <div style="border:1px solid #ccc">
    A組件:
    <span>{{elementValue}}</span>
    <input type="text" v-model="elementValue">
    <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>

<template>
  <div  style="border:1px solid #ccc">
    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>

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