Vuex的定位
在SPA单页面组件开发中,Vue的vuex和React的Redux都统称为同一状态管理。
也可以理解为将原有的 Vue实例中的data项,转变为全局变量,供各个模块使用,
任意模块中值变更后,全局响应。
在此之前的Vue组件间通信
组件间的通信,是按照父子关系去联络的。
子→父:$emit 事件传值
父→子:v-on/@ props 属性传值
对于层级复杂的多个组件间数据通信,代码就相当繁琐了。
Vuex 同一状态管理
引用Vuex 定义仓库store
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
// state
state:{
count:0
},
mutations:{
increment(){
this.state.count = this.state.count+2;
}
}
});
export default store;
vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex));
通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。
console.log(this.$store.state) //0
this.$store.commit("increment") //state = 1