1.创建大仓库:
index.ts
// createPinia引入创建大仓库
import {createPinia} from 'pinia';
// 创建仓库
const pinia = createPinia()
// 暴漏文件
export default pinia;
2.定义小仓库state类型(可不定义)
type.ts
import type { RouteRecordRaw } from "vue-router";
// 定义小仓库的state类型
export interface userState{
token:string|null;
menuRoutes:RouteRecordRaw[],
username:string,
avatar:string
}
3.小仓库配置
// 小仓库 layoput的配置
import {defineStore} from 'pinia';
let useLayoutSettingStore = defineStore('SettingStore',{
state:()=>{
return{
fold:false, //控制菜单是否收起
refsh:false //控制刷新
}
}
})
export default useLayoutSettingStore;
4.定义小仓库
//引入 创建小仓库
import { defineStore } from "pinia";
// 引入api接口
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
import type { loginFromData,LoginResponseData,UserInfoResponseData} from "@/api/user/type";
import type { userState } from "./types/type";
// 引入公共路由
import { constantRoute } from "@/router/routes";
// 引入封装的token持久化读取和修改
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
// 创建小仓库、
let useUserStore = defineStore('User', {
state: (): userState => {
return {
token: GET_TOKEN(), //唯一标识,在localStorage中持久化
menuRoutes: constantRoute, //路由菜单
username: '',
avatar: ''
}
},
actions: {
async userLogin(data: loginFromData) {
// 登录请求
let result: LoginResponseData = await reqLogin(data)
if (result.code == 200) {
this.token = (result.data as string )
// 持久化token
SET_TOKEN((result.data as string))
return 'ok'
} else {
return Promise.reject(new Error(result.data))
}
},
// 获取用户信息
async useInfo() {
let result:UserInfoResponseData = await reqUserInfo();
if (result.code == 200) {
this.username = result.data.name;
this.avatar = result.data.avatar;
return 'ok'
} else {
return Promise.reject(new Error(result.message))
}
},
// 退出登录
async userLogout() {
// 退出接口
let result:any = await reqLogout()
if (result.code == 200) {
// 清空数据
this.username = ''
this.avatar = ''
this.token = ''
// 清楚token持久化
REMOVE_TOKEN()
// 跳转
return 'ok'
}else{
return Promise.reject(new Error(result.message))
}
}
},
getters: {}
})
export default useUserStore
使用小仓库
// 引入小仓库
import useUserStore from '@/store/modules/user'
//定义
let useStore = useUserStore()
// 通过仓库提交数据
await useStore.userLogin(loginForm)