转载自 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>