[type.CHANGE_COUNT](state) {
state.count++
}
}
export default mutations
将mutation中的方法名单独作为常量提取出来,放在单独的文件中,用的时候引用相关的内容,这样非常便于管理和了解有哪些方法存在,很直观。另一方面,有时候可能需要用到action,可以使用相同的方法名,只要再引入常量的文件就行。
// action.js
import type from './mutation-type'let actions = {
[type.CHANGE_COUNT]({ commit }) {
commit(type.CHANGE_COUNT)
}
}
export default actions
怎么样,这样是不是看起来就没有写在一个文件里那么乱了。
…mapGetters和…mapActions
tab1.vue里:
// tab1.vue
<template>
<div>
<p>这是tab1的内容</p>
<em @click="add">{{count}}</em>
<p>getter:{{NewArr}}</p>
</div>
</template><script>
import { mapActions, mapGetters } from "vuex";
import type from "../store/mutation-type";
export default {
computed: {
...mapGetters([
'NewArr'
]),
count: function() {
return this.$store.state.count;
},
},
methods: {
...mapActions({
CHANGE_COUNT: type.CHANGE_COUNT
}),
add: function() {
this.CHANGE_COUNT(type.CHANGE_COUNT);
}
}
};
</script>
<style lang="" scoped>
</style>
index.js文件里:
import Vuex from 'vuex'
import Vue from 'vue'
import actions from './action'
import mutations from './mutation'
import getters from './getter'
import tab2 from './module/tab2'
import tab3 from './module/tab3'Vue.use(Vuex)
let state = {
count: 1,
arr:[]}
let store = new Vuex.Store({
state,
getters,
mutations,
actions,
modules:{
tab2,tab3
}
})
export default store
vuex提供了一种叫做辅助函数的东西,他的好处能让你在一个页面集中展示一些需要用到的东西,并且在使用的时候也可以少写一些内容,不过这个不是必须,根据自己需要取用。
需要说明的是,他们两个生效的地方可不一样。
…mapGetters写在本页面的计算属性中,之后就可以像使用计算属性一样使用getters里的内容了。
…mapActions写在本页面的methods里面,既可以在其他方法里调用,甚至可以直接写在@click里面,像这样:
<em @click="CHANGE_COUNT">{{count}}</em>酱紫,tab1里面的数字每次点击都会自增1。
mudule
vuex的文档里对于模块这部分写的比较模糊,还是得自己实际使用才能行。










