美文网首页
pinia(存储库)+ pinia-plugin-persist

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

作者: 月下小酌_dbd5 | 来源:发表于2023-05-03 16:43 被阅读0次
    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)
    
    

    相关文章

      网友评论

          本文标题:pinia(存储库)+ pinia-plugin-persist

          本文链接:https://www.haomeiwen.com/subject/urltsdtx.html