安装

参考文档: https://github.com/vuejs/vuex
vuex3的版本还没有适配vue3.0所以要安装4以上的版本
npm install --save vuex@4

初始化

  1. import { createStore } from "vuex";
  2. const store = createStore({
  3. state: {
  4. count: 0,
  5. },
  6. });
  7. export default store;

在main.ts中进行安装

  1. import store from "./store";
  2. createApp(App).use(Router).use(store).mount("#app");

读取state数据

  1. import { useStore } from "vuex";
  2. setup() {
  3. const store = useStore();
  4. console.log("count", store.state.count);
  5. }

修改state数据

  1. mutations: {
  2. add(state) {
  3. state.count++;
  4. },
  5. }
  6. store.commit("add");

getter的使用

定义

  1. getters: {
  2. doubleCount(state) {
  3. return state.count * 2;
  4. },
  5. }

使用

  1. const store = useStore();
  2. console.log("doubleCount", store.getters.doubleCount);

为state添加类型支持

添加

  1. export interface StoreStateProps {
  2. count: number;
  3. }
  4. const store = createStore<StoreStateProps>({
  5. state: {
  6. count: 0
  7. }

使用

  1. const store = useStore<StoreStateProps>();
  2. console.log("count", store.state.count);