- 安装
npm install pinia
npm i pinia-plugin-persist
- 新建store/index.ts
//store/index.ts
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const piniaStore = createPinia()
piniaStore.use(piniaPluginPersist)
export default piniaStore
- main.ts 引用
import piniaStore from "@/store";
、、、
const app = createApp(App).use(piniaStore)
、、、
- 自定义 store/accountInfoStore.ts 使用
import {defineStore} from "pinia";
export const useAccountInfoStore = defineStore('accountInfoStore', {
state:() => {
return {
hasInit: false,
token: "",
account: {} as Account,
rememberAccount: {} as {username: string, password:string},
useLeftHandler: true,
}
},
getters: {
},
actions: {
login(loginRequest: LoginRequest):Promise<LoginResponse> {
return new Promise((resolve, reject) => {
login(loginRequest).then((data) => {
this.token = data.token
}).catch(err => {
reject(err)
})
})
},
},
persist: {
enabled: true,
//持久化
strategies: [
{ storage: sessionStorage, paths: ['token', 'account'] },
{ storage: localStorage, paths: ['rememberAccount'] },
],
},
- 使用
import {useAccountInfoStore} from "@/store/accountInfoStore";
const accountInfoStore = useAccountInfoStore()
let loginRequest = {
username:1,
password:1,
uuid:'1132783737333'
}
//登录
accountInfoStore.login(loginRequest)
网友评论