Vue中非父子组件之间传值

Demo效果展示

Vue中非父子组件之间传值

 

新建一个bus.js文件,写入如下代码

 

公共bus.js

// 公共bus.js
// 非父子组件之间传值,需要定义个公共的公共实例文件bus.js,作为中间仓库来传值,不然路由组件之间达不到传值的效果
import Vue from 'vue'
export default new Vue()

 

新建一个componentA.vue文件,写入如下代码

 

组件A:

<template>
  <div class="componentA">
    <h1>我是组件A</h1>
    <button @click="MsgToB">点击</button>
  </div>
</template>

<script>
// 引入公共的bug,来做为中间传达的工具
import Bus from './bus.js'
export default {
  name: 'componentA',
  data () {
    return {
      msg: '组件A传给组件B',
      age: 5
    }
  },
  mounted () {

  },
  methods: {
    MsgToB () {
      console.log(1111)
      // 用$emit事件来传递参数
      Bus.$emit('msgToB', this.msg)
    }
  }
}
</script>

<style lang="less" scoped>
</style>

 

 

新建一个componentB.vue文件,写入如下代码

 

 组件B:

 

<template>
  <div class="componentB">
    <h1>我是组件B</h1>
    <button @click="btn">点击</button>
    <h2>{{age}}</h2>
  </div>
</template>

<script>
// 引入公共的bug,来做为中间传达的工具
import Bus from './bus.js'
export default {
  name: 'componentB',
  data () {
    return {
      msg: '',
      age: 0
    }
  },
  mounted () {
    // 用$on事件来接收参数
    Bus.$on('msgToB', (data) => {
      // data就是组件A传过来的值
      console.log(data)
    })
  },
  methods: {
    btn () {
      this.age++
    }
  }
}
</script>

<style lang="less" scoped>
</style>