vue3 使用 pinia与pinia-plugin-persistedstate 持久化数据管理

首先附上官方文档
pinia
pinia-plugin-persistedstate
怎么用官网都有说明,下面简单记录下自己在uniapp项目中使用的过程。

第一步分别安装

yarn add pinia
yarn add pinia-plugin-persistedstate
# 或者使用 npm
npm install pinia
npm i pinia-plugin-persistedstate

第二步,在store下新建文件pinia.ts文件,配置全局持久化

import {
    
     createPinia } from "pinia";
import {
    
     createPersistedState } from 'pinia-plugin-persistedstate'

const pinia = createPinia();
// 将插件添加到 pinia 实例上,全局配置持久化的storage
pinia.use(createPersistedState({
    
    
    storage: {
    
    
        getItem: (key: string) => {
    
    
            return uni.getStorageSync(key);
        },
        setItem: (key: string, value: string): void => {
    
    
            uni.setStorageSync(key, value);
        }
    },
}));

export default pinia;

第三步在main.ts中 将pinia添加到vue实例上

import {
    
     createSSRApp } from "vue";
import App from "./App.vue";
import * as Pinia from 'pinia';
import pinia from "@/store/pinia";

export function createApp() {
    
    
  const app = createSSRApp(App);
  //添加到vue实例上
  app.use(pinia);
  return {
    
    
    app,
    Pinia
  };
}

至此,配置完成了,然后就可以开始使用了,下面写个简单的案例
在store中新建user.ts文件

import {
    
     defineStore } from "pinia";

const useUserStore = defineStore("global", {
    
    
    persist: {
    
    
        paths: ["user", "userState"] // 指定需要持久化的字段
    },
    state: () => ({
    
    
        user: {
    
    
            token: "",
            user_name: "",
            user_id: "",
            role_id: "",
            nick_name: "",
            password: "",
            phone: "",
            //.......一些登陆后后端返回的字段数据
        },
        userState: {
    
    
            authed: false,
            authName: 'PUBLIC',
            homeComponent: () => ""
        }
    }),
    actions: {
    
    
        clearAuth() {
    
    
            this.$reset();
        }
    }
});

export default useUserStore;

在页面中使用

<template>
    <view class="title">我的</view>
    <view class="avatar" @tap="handleUserInfo">
        <view class="avatar_img">
            <image mode="aspectFit" :src="myInfo.avatar"></image>
        </view>
        <view class="avatar_des">
            <view class="name">{
    
    {
    
     myInfo.name }}</view>
            <view class="des">{
    
    {
    
     myInfo.postName }} {
    
    {
    
     myInfo.phone }}</view>
        </view>
    </view>
</template>
<script setup lang="ts">
import {
    
     onMounted, ref } from "vue";
import useUserStore from "@/store/user";
const userStore = useUserStore();

type MyPageType = {
    
    
    avatar: string;
    name: string;
    postName: string;
    phone: string;
}
const myInfo = ref<MyPageType>({
    
    
    avatar: "/static/avatar.png",
    name: userStore.user.real_name,
    postName: '张三',
    phone: userStore.user.phone
})
</script>

更多高级用法,请移步官网查看文档,完结撒花~~~~

猜你喜欢

转载自blog.csdn.net/qq_43227422/article/details/129163199