1. 核心想法
使用vuex进行兄弟组件通信的核心思路就是将vuex作为一个store(vuex被设计的原因之一),将每个子组件的数据都存放进去,每个子组件都从vuex里获取数据,其实就是一句话——把vuex作为一个桥
2. 具体代码
父组件App.vue
<template>
<div id="app">
<ChildA/>
<ChildB/>
</div></template><script>
import ChildA from './components/ChildA' // 导入A组件
import ChildB from './components/ChildB' // 导入B组件
export default { name: 'App', components: {ChildA, ChildB} // 注册A、B组件
}</script><style>
#app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px;
} div { margin: 10px;
}</style>子组件ChildA<template>
<div id="childA">
<h1>我是A组件</h1>
<button @click="transform">点我让B组件接收到数据</button>
<p>因为你点了B,所以我的信息发生了变化:{{BMessage}}</p>
</div></template><script>
export default {
data() { return { AMessage: 'Hello,B组件,我是A组件'
}
}, computed: {
BMessage() { // 这里存储从store里获取的B组件的数据
return this.$store.state.BMsg
}
}, methods: {
transform() { // 触发receiveAMsg,将A组件的数据存放到store里去
this.$store.commit('receiveAMsg', { AMsg: this.AMessage
})
}
}
}</script><style>
div#childA { border: 1px solid black;
}</style>子组件ChildB<template>
<div id="childB">
<h1>我是B组件</h1>
<button @click="transform">点我让A组件接收到数据</button>
<p>因为你点了A,所以我的信息发生了变化:{{AMessage}}</p>
</div></template><script>
export default {
data() { return { BMessage: 'Hello,A组件,我是B组件'
}
}, computed: {
AMessage() { // 这里存储从store里获取的A组件的数据
return this.$store.state.AMsg
}
}, methods: {
transform() { // 触发receiveBMsg,将B组件的数据存放到store里去
this.$store.commit('receiveBMsg', { BMsg: this.BMessage
})
}
}
}</script><style>
div#childB { border: 1px solid green;
}</style>vuex模块store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
// 初始化A和B组件的数据,等待获取
AMsg: '',
BMsg: ''
}
const mutations = {
receiveAMsg(state, payload) {
// 将A组件的数据存放于state
state.AMsg = payload.AMsg
},
receiveBMsg(state, payload) {
// 将B组件的数据存放于state
state.BMsg = payload.BMsg
}
}
export default new Vuex.Store({
state,
mutations
})作者:bluesboneW
来源:https://segmentfault.com/a/1190000014838912?utm_source=channel-hottest


随时随地看视频