Vuex mapState mapMutations namespaced: true 框架级映射使用总结
1.基本目录结构
src/store
|--src
|--modules
|--common.js
|--user.js
|--getters.js
|--index.js
2.引入和使用
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import common from './modules/common'
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user,
common
},
getters,
})
export default store
3.getters 模块
getters
调用写法
这里处理的数据其实和vue
中computer
计算属性一样,可以做简单运算的数据
const getters = {
userInfo: state => state.user.userInfo,
website: state => state.common.website,
…………
}
export default getters
4.模块内部写法
基本写法:
const xue= {
namespaced: true,
state:{},
getters:{}
actions:{},
mutations:{},
}
src/store/modules/user.js
import { getUserData, getRoleData } from '@/api/admin'
const user = {
namespaced: true, // 打开命名空间
state: {},
actions: {
GetUserData({ commit, state, dispatch }, page) {
return new Promise((resolve, reject) => {
getUserData(page).then(res => {
const data = res.data;
resolve(data);
})
})
},
},
mutations: {}
}
export default user
5.引入和使用
import { mapState, mapGetters,mapMutations,mapActions } from "vuex";
computed: {
...mapState('user',['sum','shool','addr','name','age']),
...mapGetters(["tag", "lockPasswd"])
},
methods: {
...mapMutations('user',['changeDetail']),
...mapActions('user',['normalizeNamespace'])
}
备注:其他引用办法
// 写法一
...mapState(['leftFocus', 'hasBg'])
// 写法二
...mapState({
'name':state=>state.user.username // user 为模块名
})
// 写法三(推荐写法)
...mapState(user, ['data1', 'data2']) // uaer 位模块名
// 写法四 原来的写法
this.$store.state.sum.xxx
基本大概现在就是这些吧