vuex辅助函数
/* 导出vuex中的mapState,mapGetters,mapMutations,mapActions方法 */
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
computed:{
/* 利用mapState方法使用拓展运算符把list,getDazhuan解构在计算属性中 */
/* ...mapState(['list']) */
/* ...mapGetters(['getDazhuan','getBenke']) */
有一种场景,vue实例化对象里的数据名和map方法出来的方法名字一致,需要改名使用一种对象的形式
...mapState({lista:'list'}) /
}
methods:{
...mapMutations(['DELNUM']),
/* this.$store.cpmmit('DELNUM',this.num) */
/* 利用mapActions方法使用拓展运算符吧actions的方法解析在methods中 ,在this中也可以找到对应解析出来的方法 */
...mapActions(['addajax']),
/* this.$store.dispatch('addajax',this.num) */
}
模块化 modules
在store目录下创建modules文件夹,创建modA.js文件。
/* 模块的局部状态 */
/* 箭头函数如果需要返回对象,需要使用()包一下 */
const state=()=>({
modaStr:'我是模块A的数据'
})
const getters={
strGetter(state){
return state.modaStr+'getter'
}
}
const mutations={
CHANGESTRA(state,payload){
state.modaStr=payload
}
}
const actions={
waitStr({commit},data){
setTimeout(() => {
commit('CHANGESTRA',data)
}, 1500);
}
}
export default{
/* 保证模块之间的数据独立运行,不会相互影响 */
namespaced:true,
state,
getters,
mutations,
actions
}
index.js文件中导入文件 import modA from '@/store/modules/modA'
模块化 modules: { modA: modA, }
mapState,mapGetters中的数据可以直接在插值中表达
mapState <h1>{{$store.state.modA.modaStr}}</h1>
mapGetters <h1>{{$store.getters['modA/strGetter']}}</h1>
mapMutations,mapActions需要在组件methods中通过方法触发
methods:{
mapMutations this.$store.commit('modA/CHANGESTRA','后来的我们没有走到一起')
mapActions this.$store.dispatch('modA/waitStr','异步处理完成')
}