Vue中如何进行非父子组件间的通信

220 阅读1分钟

Vue中父子组件间进行通信可以使用 refsrefs 或children 来进行父组件访问子组件的操作,通过$parent进行子组件访问父组件的操作(详情见文章 组件访问(父访子 与 子访父) - 掘金 (juejin.cn)), 那么如何实现非父子组件间的通信呢?基本思路如下:

使用Vue.prototype

使用prototype原型挂载属性,来作为全局变量

1.创建js文件,声明变量

let gl_value = undefined;
export default {gl_value};

2.main.js文件中添加

lue from '../static/js/commonvue'
Vue.prototype.$GLOBAL = gl_value;

3.调用
组件A

this.$GLOBAL.gl_value = “组件A的值”; //修改值
}

组件B

mounted() {
this.msg = this.$GLOBAL.gl_value//接收值
}

使用vuex

大致思路和使用prototype原型挂载属性相同,我们可以把公用的数据使用vuex来进行存储,可以在项目中的任何一个组件里进行获取、进行修改,并且你的修改可以得到全局的响应变更。

.创建一个js文件

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 存储共用的数据
export default new Vuex.Store({
state:{
value:"vuex值"
}
})

2.在main.js文件中引入

import store from '../static/js/commonvue'
new Vue({
el: '#app',
router,
store,
components: { App },
template: ''
})

3.使用时直接调用
组件A

mounted() {
this.$store.state.value = “组件A的值”; //修改值
}

组件B

mounted() {
this.msg = this.$store.state.value//接收值
}