state-management.md 8.66 KB

状态管理

Venus Admin 使用 Pinia 进行状态管理,提供类型安全的状态管理方案。

为什么选择 Pinia?

Pinia 是 Vue 的新一代状态管理库,具有以下优势:

  • ✅ 完整的 TypeScript 支持
  • ✅ 更简洁的 API
  • ✅ 模块化设计
  • ✅ 支持 Composition API
  • ✅ 开发工具支持

创建 Store

基础用法

// src/store/modules/counter.ts
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  // 状态
  state: () => ({
    count: 0,
  }),

  // 计算属性
  getters: {
    doubleCount: (state) => state.count * 2,
  },

  // 方法
  actions: {
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
  },
});

使用 Composition API

import { ref, computed } from 'vue';
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', () => {
  // state
  const count = ref(0);

  // getters
  const doubleCount = computed(() => count.value * 2);

  // actions
  function increment() {
    count.value++;
  }

  function decrement() {
    count.value--;
  }

  return {
    count,
    doubleCount,
    increment,
    decrement,
  };
});

在组件中使用

<template>
  <div>
    <p>计数: {{ counter.count }}</p>
    <p>双倍计数: {{ counter.doubleCount }}</p>

    <button @click="counter.increment()">增加</button>
    <button @click="counter.decrement()">减少</button>
  </div>
</template>

<script setup lang="ts">
import { useCounterStore } from '@/store/modules/counter';

const counter = useCounterStore();
</script>

核心 Store

useUserStore

用户信息管理。

// src/store/modules/user.ts
import { defineStore } from 'pinia';
import type { UserInfo } from '@/types';

interface UserState {
  userInfo: UserInfo | null;
  token: string | null;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userInfo: null,
    token: null,
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    getUserInfo: (state) => state.userInfo,
  },

  actions: {
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
    },

    setToken(token: string) {
      this.token = token;
    },

    async login(credentials: LoginCredentials) {
      const { data } = await loginApi(credentials);
      this.setUserInfo(data.userInfo);
      this.setToken(data.token);
      return data;
    },

    async logout() {
      await logoutApi();
      this.reset();
    },

    reset() {
      this.userInfo = null;
      this.token = null;
    },
  },

  persist: {
    key: 'user',
    paths: ['userInfo', 'token'],
  },
});

useAuthStore

权限管理。

// src/store/modules/auth.ts
import { defineStore } from 'pinia';

interface AuthState {
  roles: string[];
  authorities: string[];
  isDynamicRouteAdded: boolean;
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    roles: [],
    authorities: [],
    isDynamicRouteAdded: false,
  }),

  getters: {
    getRoles: (state) => state.roles,
    getAuthorities: (state) => state.authorities,
  },

  actions: {
    setRoles(roles: string[]) {
      this.roles = roles;
    },

    setAuthorities(authorities: string[]) {
      this.authorities = authorities;
    },

    hasAuthority(authority: string | string[]): boolean {
      const authorities = Array.isArray(authority) ? authority : [authority];

      if (this.roles.includes('super-admin')) {
        return true;
      }

      return authorities.some(auth => this.authorities.includes(auth));
    },

    hasRole(role: string | string[]): boolean {
      const roles = Array.isArray(role) ? role : [role];
      return roles.some(r => this.roles.includes(r));
    },
  },

  persist: {
    key: 'auth',
    paths: ['roles', 'authorities'],
  },
});

useAppStore

应用配置管理。

// src/store/modules/app.ts
import { defineStore } from 'pinia';

interface AppState {
  collapsed: boolean;
  theme: 'light' | 'dark';
  locale: string;
}

export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    collapsed: false,
    theme: 'light',
    locale: 'zh-CN',
  }),

  actions: {
    toggleCollapsed() {
      this.collapsed = !this.collapsed;
    },

    setTheme(theme: 'light' | 'dark') {
      this.theme = theme;
    },

    setLocale(locale: string) {
      this.locale = locale;
    },
  },

  persist: {
    key: 'app',
  },
});

状态持久化

使用 pinia-plugin-persistedstate 插件实现状态持久化:

安装插件

pnpm add pinia-plugin-persistedstate

配置插件

// src/store/index.ts
import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);

export default pinia;

使用持久化

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
  }),

  persist: {
    // 存储的键名
    key: 'user',
    // 存储的字段
    paths: ['userInfo'],
    // 存储方式
    storage: localStorage,
  },
});

Store 之间的通信

在 Store 中使用其他 Store

import { defineStore } from 'pinia';
import { useUserStore } from './user';

export const useAuthStore = defineStore('auth', {
  actions: {
    async checkPermission() {
      const userStore = useUserStore();
      const userInfo = userStore.userInfo;

      // 使用 userInfo 进行权限检查
    },
  },
});

监听其他 Store 的变化

import { watch } from 'vue';
import { useUserStore } from '@/store/modules/user';

const userStore = useUserStore();

// 监听 userInfo 变化
watch(
  () => userStore.userInfo,
  (newValue, oldValue) => {
    console.log('用户信息变化', newValue, oldValue);
  }
);

异步操作

export const useDataStore = defineStore('data', {
  state: () => ({
    list: [],
    loading: false,
  }),

  actions: {
    async fetchList() {
      this.loading = true;
      try {
        const { data } = await getListApi();
        this.list = data;
      } catch (error) {
        console.error('获取列表失败', error);
      } finally {
        this.loading = false;
      }
    },
  },
});

重置状态

export const useDataStore = defineStore('data', {
  state: () => ({
    data: null,
  }),

  actions: {
    reset() {
      // 方式 1: 手动重置
      this.data = null;

      // 方式 2: 使用 $reset
      this.$reset();
    },
  },
});

最佳实践

1. 模块化组织

按功能模块组织 Store:

store/
├── modules/
│   ├── user.ts      # 用户相关
│   ├── auth.ts      # 权限相关
│   ├── app.ts       # 应用配置
│   └── ...
└── index.ts         # Store 实例

2. 类型安全

充分利用 TypeScript 类型系统:

interface UserState {
  userInfo: UserInfo | null;
  token: string | null;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userInfo: null,
    token: null,
  }),
});

3. 避免直接修改状态

使用 actions 修改状态,而不是直接修改:

// ❌ 不推荐
const userStore = useUserStore();
userStore.userInfo = newUserInfo;

// ✅ 推荐
const userStore = useUserStore();
userStore.setUserInfo(newUserInfo);

4. 合理使用持久化

只持久化必要的数据:

persist: {
  key: 'user',
  paths: ['userInfo', 'token'], // 只持久化这两个字段
}

5. 错误处理

在 actions 中处理错误:

actions: {
  async fetchData() {
    try {
      const data = await api.getData();
      this.data = data;
    } catch (error) {
      console.error('获取数据失败', error);
      // 可以设置错误状态
      this.error = error;
    }
  },
}

调试

使用 Vue DevTools

Pinia 支持 Vue DevTools,可以:

  • 查看所有 Store 的状态
  • 追踪状态变化
  • 时间旅行调试

日志打印

import { watch } from 'vue';

export const useDebugStore = defineStore('debug', () => {
  const state = ref({});

  // 在开发环境打印状态变化
  if (import.meta.env.DEV) {
    watch(
      state,
      (newValue) => {
        console.log('State changed:', newValue);
      },
      { deep: true }
    );
  }

  return { state };
});

下一步