
小程序开发模版_怎么使用vuex完成兄弟组件通信
2021-01-08 11:38
前言
vuex主要是是做数据交互,父子组件传值可以很容易办到,但是兄弟组件间传值,需要先将值传给父组件,再传给子组件,异常麻烦。
下面这篇文章就来给大家介绍下vuex兄弟组件通信的方法,下面话不多说了,来一起看看详细的介绍吧
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.$mit('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.$mit('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 })
我把所有的代码+注释都放在github了,,
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对凡科的支持。
扫描二维码分享到微信