通过一个简单的例子学会vuex与模块化(2)
将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的文档里对于模块这部分写的比较模糊,还是得自己实际使用才能行。
在本例子中,我设置了两个模块:tab2和tab3,分别对应着同名的两个组件,当然,我这样只是为了测试,实际看tab2就可以。
// module/tab2.js
const tab2 = {
state: {
name:`这是tab2模块的内容`
},
mutations:{
change2(state){
state.name = `我修改了tab2模块的内容`
}
},
getters:{
name(state,getters,rootState){
console.log(rootState)
return state.name + ',使用getters修改'
}
}
}
export default tab2;
内容版权声明:除非注明,否则皆为本站原创文章。
