VUEX 就是做全局变量管理的,声明全局变量,并提供 getter 和 setter
1、安装vuex
npm install vuex –save
2、src下创建store文件夹,其中创建 index.js ,内容如下:
import Vue from 'vue';
import Vuex from 'vuex';
// 需要注册vuex到vue中
Vue.use(Vuex);
// 使用 es6 语法把vuex的实例对象输出
export default new Vuex.Store({
})
3、在main.js中注册vuex
import store from './store'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
4、在state中声明全局变量
export default new Vuex.Store({
// 在state中去声明全局变量,在任何一个 component中通过可以通过 this.$store.state.count 访问
// 似乎不可以直接通过 this.$store.state.count = xxx 的方式改变state中的状态
state: {
count: 0
},
...
5、getter
// 在getters中声明state中变量的计算函数,缓存计算后的数据
// 1) 可以通过 this.$store.state.count 访问count
// 2) 可以通过 this.$store.getters.getCount 返回计算值
getters: {
// 接受state作为参数, 每次 count发生变化时, 都会被调用
getCount: state => {
console.log('the state count : ' + state.count);
return state.count+1;
}
},
6、setter
// ------------- 以下几个相当于setter -------------
// actions是异步的改变state状态,而Mutations是同步改变状态
// 可以在任何一个 component中通过
// 1) this.$store.commit('addNumCount', 5); 修改count值
// 2) this.$store.dispatch('addNumCount', 5); 去触发actions操作来改变state中的值。
mutations: {
addCount: state => {
++state.count;
},
// mutations的第一个参数即为 state 对象,并且可以向mutation传入额外的参数
addNumCount: (state, n) => {
state.count += n;
},
},
actions: {
addCount: context => {
// 调用 mutation
context.commit('addCount');
},
addNumCount: (context, n) => {
context.commit('addNumCount', n);
}
}
7、mapState
在任何组件中
import {mapState} from 'vuex';//用import引入mapState。
...
computed:mapState({
count:state=>state.count //理解为传入state对象,返回state.count值
}),
//或者通过mapState的数组来赋值,如下:
computed:mapState(["count"])
//然后页面中就可以如此使用了:
<div>
<hr/>
<h3>{{count}}</h3>
<div>
<button @click="$store.commit('addCount')">+</button>
</div>
</div>
//否则需要 $store.state.count:
<div>
<hr/>
<h3>{{$store.state.count}}</h3>
<div>
<button @click="$store.commit('addCount')">+</button>
</div>
</div>
8、mapMutations
实际开发中我们也不喜欢看到$store.commit( )这样的方法出现,我们希望跟调用模板里的方法一样调用。
例如:@click=”addCount” 就和没引用vuex插件一样。
在组件中
import { mapState,mapMutations } from 'vuex';
...
methods:mapMutations([
'addCount','addNumCount'
]),
//也可这么写:
methods:{
...mapMutations({
add: 'addNumCount' ,// 将this.add() 映射为 this.$store.commit('addNumCount')
})
},
...
<button @click="addNumCount(10)">+10</button>
<button @click="add(10)">+10</button>
9、mapGetters
import { mapState,mapMutations,mapGetters } from 'vuex';
//在computed属性中加入mapGetters
...mapGetters(["count"])
10、mapActions 辅助函数
import { mapState,mapMutations,mapGetters,mapActions } from 'vuex';
methods:{
...mapMutations({
add: 'addNumCount' ,// 将this.add() 映射为 this.$store.commit('addNumCount')
})
...mapActions(['addCount','addNumCount'])
},
11、module模块组
如果全局变量太多,需要进行分组,使用module进行分组
const stateA={
count:0
}
const stateB={
count: 99
}
const moduleA={
stateA
}
const moduleB={
stateB
}
export default new Vuex.Store({
modules:{a:moduleA, b:moduleB}
})
//模块中调用:
<h3>{{$store.state.a.count}}</h3>
或
computed:{
count(){
return this.$store.state.a.count;
}
},