pinia(存储库)+ pinia-plugin-persist

2023-05-03  本文已影响0人  月下小酌_dbd5
  1. 安装
npm install pinia
npm i pinia-plugin-persist
  1. 新建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
  1. main.ts 引用
import piniaStore from "@/store";
  、、、
  const app = createApp(App).use(piniaStore)
  、、、
  1. 自定义 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'] },
        ],
    },
  1. 使用
import {useAccountInfoStore} from "@/store/accountInfoStore";

const accountInfoStore = useAccountInfoStore()
  let loginRequest = {
    username:1,
    password:1,
    uuid:'1132783737333'
}
//登录
  accountInfoStore.login(loginRequest)

上一篇下一篇

猜你喜欢

热点阅读