安装
参考文档: https://github.com/vuejs/vuex
vuex3的版本还没有适配vue3.0所以要安装4以上的版本npm install --save vuex@4
初始化
import { createStore } from "vuex";
const store = createStore({
state: {
count: 0,
},
});
export default store;
在main.ts中进行安装
import store from "./store";
createApp(App).use(Router).use(store).mount("#app");
读取state数据
import { useStore } from "vuex";
setup() {
const store = useStore();
console.log("count", store.state.count);
}
修改state数据
mutations: {
add(state) {
state.count++;
},
}
store.commit("add");
getter的使用
定义
getters: {
doubleCount(state) {
return state.count * 2;
},
}
使用
const store = useStore();
console.log("doubleCount", store.getters.doubleCount);
为state添加类型支持
添加
export interface StoreStateProps {
count: number;
}
const store = createStore<StoreStateProps>({
state: {
count: 0
}
使用
const store = useStore<StoreStateProps>();
console.log("count", store.state.count);