Article From:https://www.cnblogs.com/houfee/p/9965290.html

index.html:

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

index.js

// Import Vue
import Vue from 'vue/dist/vue.js'

// Import custom component templates
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>This is GG. Vue file content & lt; / H1 & gt;Button@click= "sendMsgToDD" & gt; pass value to younger brother & lt; / button>< /div>≪ /template>< script>// Import Eventbus
import eventbus from './Eventbus.js'
export default {
  data() {
    return {
      GGmsg: 'This is the value of GG.
    }
  },
  methods: {
    sendMsgToDD() {
      // In the Brother Component,
      // Call the $emit method of eventbus to send the data out
      eventbus.$emit('transmit', this.GGmsg)
    }
  }
}
</script>

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

DD.vue

<template>
  <div>
    <h1>This is the DD. Vue file content & lt; / H1 & gt;Gt; H2 & gt; value of received GG - {msgFromGG} & lt; / H2 & gt;< /div>< /template>< script>// Import Eventbus
import eventbus from './Eventbus.js'
export default {
  data() {
    return {
      msgFromGG: ''
    }
  },
  created() {
    // By the $on method of eventbus
    //,You can bind custom events for instance objects.
    eventbus.$on('transmit', data => {
      console.log('My brother received the data'plus'. 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()

 

Link of this Article: Vue.js(10) – Brothers share data

Leave a Reply

Your email address will not be published. Required fields are marked *