vue 兄弟组件的信息传递的方法实例详解

2020-06-13 10:25:33易采站长站整理

前言

兄弟组件的信息传递有三种方式:

1.vuex 传递。

会将信息公有化。

此方法可在所有组件间传递数据。

2.建立Vue 实例模块传递数据。

Vue 实例模块会成为共用的事件触发器。

其通过事件传递的信息不回被公有化。

3.建立事件链传递数据。

一个兄弟组件通过事件将信息传给兄弟组件共有的父组件。

父组件再将信息通过属性传递给另一个兄弟组件。

若兄弟组件不是亲兄弟,而是堂兄弟,也就是他们有一个共同的爷爷,那么此方法会使程序变得繁琐。

一,vuex 传递数据

1.安装vuex

npm install vuex --save

2.store.js


import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store=new Vuex.Store({
state:{
msgFromA:'A 还没说话',
msgFromB:'B 还没说话'
},
getters:{
},
mutations:{
msgAChange(state,msg){
state.msgFromA=msg;
},
msgBChange(state,msg){
state.msgFromB=msg;
},
}
})

3.子组件A.vue


<template>
<div class="a">
<h3>A 模块</h3>
<p>B 说:{{msgFromB}}</p>
<button @click="aSay">A 把自己的信息传给B</button>
</div>
</template>

<script>
export default {
data () {
return {
msg:'我是A',
}
},
methods:{
aSay(){
this.$store.commit('msgAChange', this.msg);
}
},
computed: {
msgFromB() {
return this.$store.state.msgFromB;
}
}
}
</script>

4.子组件B.vue


<template>
<div class="b">
<h3>B 模块</h3>
<p>A 说:{{msgFromA}}</p>
<button @click="bSay">B 把自己的信息传给A</button>
</div>
</template>

<script>
export default {
data () {
return {
msg:'我是B'
}
},
methods:{
bSay(){
this.$store.commit('msgBChange', this.msg);
}
},
computed: {
msgFromA() {
return this.$store.state.msgFromA;
}
}
}
</script>

二,Vue 实例模块传递数据

1.建立Vue 实例模块 bus.js


import Vue from 'vue'
export default new Vue();

2.子组件 A.vue


<template>
<div class="a">
<h3>A 模块</h3>