vuex 在3.0中的使用和2.0的使用几乎相同。
记录下使用过程。
安装vuex
npm i -s-d vuex
- 创建文件夹
store
创建index文件
import Vuex from 'vuex'
import getters from './getters';
import common from './modules/common';
interface stateType {
user: any;
common: any;
}
const store = new Vuex.Store({
modules: {
common,
},
getters,
})
export default store;
模块化
- 创建一个modules文件夹
- 创建common文件 也可使用createStore传入一个对象创建。
import { Module } from "vuex";
interface commonType {
login: boolean;
theme: string;
}
const common: Module<any, any> = {
namespaced: true,
state: {
login: false,
theme: 'default',
},
mutations: {
setLogin(state: commonType, login) {
state.login = login;
},
setTheme(state: commonType, theme) {
state.theme = theme;
// 切换主题
}
},
actions: {
getAuth(context) {
context.commit("setLogin");
}
},
getters: {
getLogin(state: commonType) {
return state.login;
},
getTheme(state: commonType) {
return state.theme;
}
}
}
export default common;
-使用
import { useStore } from 'vuex';
const store = useStore();
console.log(store);
console.log(store.getters['common/getLogin']);
store.commit('common/setLogin', true);
console.log(store.getters['common/getLogin']);
store.dispatch('name')
- actions 与mutations的区别
- 异步和同步。