Vue兄弟之间传值

转载自 https://www.jianshu.com/p/661634c1af9b ,感谢作者 !!!
原理

vue非父子通信一般常用的方法有 EventBus 和 Vuex,这里讲下bus
过实例化一个Vue对象( 比如bus = new Vue() )作为母线,在组件中通过事件将参数传递出去
( bus.$emit(event, [...args]) ),然后在其他组件中再通过bus( 这里按照刚前面实例化Vue对象后的叫法 )来监听此事件并接受参数( bus.$on(event, callback) )。
PS: 共用同一个Vue的实例( new Vue() ),通过此实例进行事件传递参数,在其他组件中监听此事件并且接收参数实现通信。

bus.js

//(实例化一个Vue对象并暴露)
import Vue from 'vue'
const bus = new Vue()
export default bus

组件Hello.vue

<template>
  <div class="hello">
    <h1>参数:{{ number }}</h1>
    <button @click="sendParam()">发送</button>
  </div>
</template>
<script>
import bus from './bus'
export default {
  data () {
    return {
      number: 123
    }
  },
  methods: {
    sendParam () {
      bus.$emit('getParam', this.number)
    }
  }
}
</script>

组件World.vue

<template>
  <div class="hello">
    <h1>接受参数{{ number }}</h1>
  </div>
</template>
<script>
import bus from './bus'
export default {
  data () {
    return {
      number: 0
    }
  },
  created () {
    bus.$on('getParam', param => {
      this.number = param
    })
  },
  beforeDestroy () {
    bus.$off('getParam')
  }
}
</script>

组件Home.vue (同时引入Hello.vue组件和World.vue组件)

<template>
  <div class="home">
    <hello></hello>
    <world></world>
  </div>
</template>

<script>
import Hello from '@/components/Hello'
import World from '@/components/World'
export default {
  name: 'Home',
  data () {
    return {
    }
  },
  components: {
    Hello,
    World
  }
}
</script>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值