vuex4.x+ts的簡單用法
vue3已經(jīng)出來有段時間了,vuex4.x最近也剛剛出來,然后就想著用vue3+ts做一個項(xiàng)目
這篇文章用來記錄vuex4.x 中module的使用
定義模塊
命名空間
namespaced: true命名空間 防止模塊命名沖突
設(shè)置后調(diào)用mutations和action需要
'模塊名/方法' 例如app/setMenuList
export const app = {
namespaced: true, // 防止模塊命名沖突 設(shè)置后調(diào)用mutations和action需要
// '模塊名/方法' 例如 app/setMenuList
state: {
menuList: [],
},
getters: {
menuList: (state: any) => state.menuList,
},
mutations: {
setMenuList(state: { menuList: any }, menu: any) {
state.menuList = menu
}
},
actions: {
menuFn(store: any,data:any) {
store.commit('setMenuList', data)
},
}
}
使用模塊
- 在store/index.ts 文件中使用app模塊
import { createStore } from "vuex";
import {app} from './modules/app'
export default createStore({
state: {},
mutations: {},
actions: {},
modules: {
app
},
});
訪問(在vue文件中使用)
一、加命名空間訪問方式
- 頁面中獲取state中值
const menuList = store.state.app.menuList
- getter
const menuList = store.getters['app/menuList']
- mutations
store.commit('app/setMenuList', '要修改的數(shù)據(jù)')
- action
store.dispatch('app/menuFn', '要修改的數(shù)據(jù)')
二、不加命名空間訪問方式
- 頁面中獲取state中值
const menuList = store.state.app.menuList
- getter
const menuList = store.getters.menuList
- mutations
store.commit('setMenuList', '要修改的數(shù)據(jù)')
- action
store.dispatch('menuFn', '要修改的數(shù)據(jù)')