前言
ts
中使用 pinia
和 Vue3
基本一致,唯一的不同点在于,需要根据接口文档给 state
标注类型,也要给 actions
标注类型;- 以下都是 组合式API 的写法,选项式API 的写法大家可以去官网看看;
- Pinia;
- 持久化插件 – pinia-plugin-persistedstate;
一、定义类型文件
二、创建 store
- 目标文件:
src/stores/user.ts
; - 代码展示:
import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { User } from '@/types/user';
export const useUserStore = defineStore('user', () => {
const userInfo = ref<User>();
const setUserInfo = (u: User) => {
userInfo.value = u;
};
const delUserInfo = () => {
userInfo.value = void 0;
}
return { userInfo, setUserInfo, delUserInfo }
});
三、实现 Pinia 的持久化
- 以往做法:
- 按照以前的做法是自己手写封装一个函数(
setStorage()、getStorage()、delStorage()
),需要使用的时候进行导入使用; - 这种做法太麻烦了,在
Vue3
中我们可以安装一个插件,进行配置,会自动帮我们实现 Pinia
的持久化;
3.1、安装 Pinia
持久化插件:
pnpm i pinia-plugin-persistedstate
yarn add pinia-plugin-persistedstate
npm i pinia-plugin-persistedstate
3.2、将插件添加到 Pinia
的实例上
3.3、在 Store
中使用
- 给
defineStore()
添加第三个参数(配置对象); - 代码展示:
import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { User } from '@/types/user';
export const useUserStore = defineStore('user', () => {
const userInfo = ref<User>();
const setUserInfo = (u: User) => {
userInfo.value = u;
};
const delUSerInfo = () => {
userInfo.value = void 0;
}
return { userInfo, setUserInfo, delUserInfo }
}, { persist: true });
3.4、验证
- 在
App.vue
中随便定义两个按钮;模拟 登录和 退出登录; - 将
useUserStore
导入到 App.vue
中,调用 setUserInfo() 和 delUserInfo()
,查看 localStorage
;
四、仓库(store)统一管理
4.1、pinia
独立维护
- 以往:
- 初始化代码都在
main.ts
中,仓库代码在 stores
文件夹中,代码分散职能不单一;
- 优化处理:
- 由
stores
统一维护,在 stores/index.ts
中完成 pinia
的初始化,交付 main.ts
使用;
- 代码展示:
- 目标文件:
src/stores/index.ts
;import { createPinia } from 'pinia';
import persist from 'pinia-plugin-persistedstate';
const pinia = createPinia();
pinia.use(persist);
export default pinia;
- 目标文件:
src/main.ts
;import { createApp } from 'vue';
import pinia from '@/stores';
import App from './App.vue';
const app = createApp(App);
app.use(pinia);
app.mount('#app');
4.2、仓库(store
)统一导出
- 以往:
- 使用一个仓库
import { useUSerStore } from '@/stores/user.ts';
不同仓库路径不一致; - 在每次导入的时候,都需要使用不同的路径,不方便;
- 优化处理:
- 由
stores/index.ts
统一导出,导入路径统一 @/stores
,而且仓库维护在 src/stores/modules
中;
- 代码展示: