Vuex 是一个专为 Vue.js 应用程序开发的状态管理库,用于保存用用程序的状态,即信息或数据,使得Vuex使应用程序的所有组件可以共享数据。每一个 Vuex 应用的核心就是 store(仓库),包含着你的应用中大部分的状态 ( state ),改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。
<script> const store = new Vuex.Store({ //定义状态,并赋予初始值 state:{ msg:'Vuex的使用', count:0 }, //使用getter来返回状态 getters:{ msg(state){ return state.msg; }, count(state){ return state.count; } }, //可以理解为其他语言中的setter,改变状态的值,此处为把传进来的参数step累加到count中 mutations:{ increment(state,step){ state.count += step; } }, //模拟服务器延迟1秒 //通过commit调用来触发mutations对象中的increment方法,并把参数step传递给increment actions:{ increment(context,step){ setTimeout(function(){ context.commit('increment',step); },1000); } }, }); //创建Vue实例 let vm = new Vue({ el:'#app', computed:{ //可以直接通过计算属性直接获取store.state中的状态 msg(){ return store.state.msg; } //通过计算属性来返回getters中的count counter(){ return store.getters.count; } }, methods:{ increment(){ //调用dispatch方法来派发actions中的increment方法,并把参数2传递给increment store.dispatch('increment',2); } } }); </script>
Vuex为我们提供了一些辅助工具,如mapStates,mapGetters,mapMutations,mapActions,从而来减少繁杂的工作量。
对于使用mapStates,mapGetters,可以把所有的state,getter添加到计算属性中,而不用向上面代码那样逐个添加。
在使用这些助手时,必须引入。拿mapGetters举例,其他类似。
import {mapGetters} from 'vuex';
代码演示:
computed:{ ...mapState{[ 'state1', 'state2', ]}, ...mapGetters{[ 'count1', 'count2', ]} }
对于mapMutations,mapActions,可以在methods属性中使用,把多个mutation和action映射到应用程序。
代码演示:
methods:{ ...mapMutations([ //mut1将this.mut1()映射到this.$store.commit('mut1'),mut2类似 //这样就不同创建每个方法,派发每个action 'mut1', 'mut2' ]) }
代码演示:
methods:{ ...mapActions([ //act1将this.act1()映射到this.$store.dispatch('act1'),act2类似 'act1', 'act2' ]) }
当应用程序很大时,需要划分模块,Vuex.Store实例中将增加mudules对象。
把state,getter,mutation,action对象创建在一个单独的xxx.js文件中,xxx.js在modules目录下。
代码演示:
const state = { state1:{} }; const getters = { get1:state => state.state1 }; const actions = { initState:{} }; const mutations = { setState:{} }; //导出以上四个对象 export default{ state, getters, mutations, actions }
使用模块,在yyy.js文件中引入模块,yyy.js在store目录下。
代码演示:
import Vue from 'vue'; impoet Vuex from 'vuex'; import xxx from './modules/xxx'; Vue.use(Vuex); export const store = new Vuex.Store({ modules:{ //对应上面引入的xxx xxx } });
另外,由于Vuex中所有内容共享相同的全局名称空间,当在两个不同文件中分别命名相同的state或getter或mutation或action,就会发生冲突,报错duplicate getter key。
可以在Vuex.store文件顶部设置namespaced:true,用于分解每个名称空间的模块。