Vue.js(10)- 兄弟组件共享数据

index.html:

  <div id="app">
    <p>这是index.html</p>
    <my-gg></my-gg>
    <hr>
    <my-dd></my-dd>
  </div>

index.js

// 导入vue
import Vue from 'vue/dist/vue.js'

// 导入自定义组件模板
import GG from './GG.vue'
import DD from './DD.vue'

const vm = new Vue({
  el: '#app',
  data: {
  },
  components: {
    'my-gg': GG,
    'my-dd': DD
  }
})

GG.vue

<template>
  <div class="one">
    <h1>这是GG.vue文件内容</h1>
    <button @click="sendMsgToDD">传值给弟弟</button>
  </div>
</template>

<script>
// 导入Eventbus
import eventbus from './Eventbus.js'
export default {
  data() {
    return {
      GGmsg: '这是GG的值'
    }
  },
  methods: {
    sendMsgToDD() {
      // 在 哥哥组件中,
      // 调用 eventbus 的 $emit 方法,把数据发送出去
      eventbus.$emit('transmit', this.GGmsg)
    }
  }
}
</script>

<style lang="less" scoped>
  .one {
    border: 1px solid red;
    h1 {
    color: red;
  }
  }
</style>

DD.vue

<template>
  <div>
    <h1>这是DD.vue文件内容</h1>
    <h2>接收GG的值---{{msgFromGG}}</h2>
  </div>
</template>

<script>
// 导入Eventbus
import eventbus from './Eventbus.js'
export default {
  data() {
    return {
      msgFromGG: ''
    }
  },
  created() {
    // 通过 eventbus 的 $on 方法
    //,可以为实例对象,绑定 自定义事件;
    eventbus.$on('transmit', data => {
      console.log('弟弟接收到了数据' + data)
      this.msgFromGG = data
    })
  }
}
</script>

<style lang="less" scoped>
div {
  border: 2px dashed purple;
  h1 {
    color: green;
  }
}
</style>

Eventbus.js

import Vue from 'vue'

export default new Vue()

猜你喜欢

转载自www.cnblogs.com/houfee/p/9965290.html