刘洋博客
猥琐发育别浪
nuxt3 pinia 持久化
admin ( 5小时前)| 400次阅读

nuxt3 pinia 持久化插件pinia-plugin-persistedstate

pinia-plugin-persistedstate github
pinia-plugin-persistedstate nuxt文档

 "@pinia/nuxt": "^0.4.0",
 "pinia": "^2.0.18",
 "pinia-plugin-persistedstate": "^2.1.1",

安装依赖

npm i pinia-plugin-persistedstate pinia @pinia/nuxt --save
or
pnpm i pinia-plugin-persistedstate pinia @pinia/nuxt --save
or 
yarn add pinia-plugin-persistedstate pinia @pinia/nuxt --save

nuxt.config.ts

buildModules: [...,'@pinia/nuxt']

plugins->新建 persistedstate.client.ts

import { createPersistedState } from 'pinia-plugin-persistedstate'

export default defineNuxtPlugin(nuxtApp => {
  nuxtApp.$pinia.use(createPersistedState())
})

composables->新建ts文件 xxx.ts

import { defineStore } from "pinia";
export const usePageStore = defineStore({
  id: 'page',
  // persist: true, // 使用该插件,开启数据缓存 或者下面写法
  persist: {
    //key的名称
    key: 'pageData',
    // 此处 如果 在nuxt3中直接使用 localStorage 或 sessionStorage 会报一个错
    storage: process.client ? localStorage : null
  },
  state() {
    return {
      data: {}
    }
  },
  actions: {
    setName(data: any) {
      this.data = data
    },
  },
});

vue 中使用

<template>
  <div>
    <h2>{{ info.title }}</h2>
  </div>
</template>

<script setup lang="ts">
const usePage = usePageStore();
const info: any = ref(usePage.data); //这里nuxt3控制台有个提示 - 客户端和服务端显示不一样--

控制台的部分提示如下
Hydration text content mismatch in <h2>:
- Client: 
- Server: xxxx

</script>

我这里就只用于 客户端 就这样写了
如有好的解决方法望告知

<template>
  <div>
    <h2>{{ info.title }}</h2>
  </div>
</template>

<script setup lang="ts">
const usePage = usePageStore();
const info: any = reactive({});
// 客户端显示
onMounted(() => {
  Object.assign(info, usePage.data);
});
</script>

这里persist 看代码有三种写法

import { StateTree, PiniaPluginContext } from 'pinia';

declare type StorageLike = Pick<Storage, 'getItem' | 'setItem'>;
interface Serializer {
    /**
     * Serializes state into string before storing
     * @default JSON.stringify
     */
    serialize: (value: StateTree) => string;
    /**
     * Deserializes string into state before hydrating
     * @default JSON.parse
     */
    deserialize: (value: string) => StateTree;
}
interface PersistedStateOptions {
    /**
     * Storage key to use.
     * @default $store.id
     */
    key?: string;
    /**
     * Where to store persisted state.
     * @default localStorage
     */
    storage?: StorageLike;
    /**
     * Dot-notation paths to partially save state. Saves everything if undefined.
     * @default undefined
     */
    paths?: Array<string>;
    /**
     * Customer serializer to serialize/deserialize state.
     */
    serializer?: Serializer;
    /**
     * Hook called before state is hydrated from storage.
     * @default null
     */
    beforeRestore?: (context: PiniaPluginContext) => void;
    /**
     * Hook called after state is hydrated from storage.
     * @default undefined
     */
    afterRestore?: (context: PiniaPluginContext) => void;
}
declare type PersistedStateFactoryOptions = Pick<PersistedStateOptions, 'storage' | 'serializer' | 'afterRestore' | 'beforeRestore'>;
declare module 'pinia' {
    interface DefineStoreOptionsBase<S extends StateTree, Store> {
        /**
         * Persist store in storage.
         * @see https://github.com/prazdevs/pinia-plugin-persistedstate
         */
        persist?: boolean | PersistedStateOptions | PersistedStateOptions[];
    }
    interface PiniaCustomProperties {
        /**
         * Rehydrates store from persisted state
         * Warning: this is for advances usecases, make sure you know what you're doing.
         * @see https://github.com/prazdevs/pinia-plugin-persistedstate
         */
        $hydrate: (opts?: {
            runHooks?: boolean;
        }) => void;
    }
}

export { PersistedStateFactoryOptions as P, PersistedStateOptions as a };
共 1 条评论
淄博漏水检测
#4

感谢分享,赞一个

2月前
到底啦