官方文档:https://seb-l.github.io/pinia-plugin-persist/#vue3
安装:npm i pinia-plugin-persist --save
使用,注意是pinia.use(piniaPersist)
安装:npm i pinia-plugin-persist --save
使用,注意是pinia.use(piniaPersist)
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia';
import piniaPersist from 'pinia-plugin-persist'const app = createApp(App);
const pinia = createPinia();
pinia.use(piniaPersist);
app.use(pinia);
app.mount('#app');
实际测试发现一个问题,不能单独创建一个文件,把createPinia独立出去,然后再导入到main.js中,如果在单独的文件中 pinia.use(piniaPersist),导致本地存储失效;如果导入main.js中后再use,会报错:pinia无use函数,解决办法是导出一个函数,函数的参数是app,在main.js中导入这个函数,然后调用,把app传参进去就好了。下面代码是使用了另一个插件pinia-plugin-persistedstate
import { createPinia } from 'pinia'; import { createPersistedState } from 'pinia-plugin-persistedstate'; export const pinia = createPinia(); pinia.use(createPersistedState({ serializer: { // 指定参数序列化器 serialize: JSON.stringify, deserialize: JSON.parse, } })); // export default pinia; export function usePiniaStore(app) { app.use(pinia);//注册给app }
main.js中
import { createApp } from 'vue'
import { createApp } from 'vue'
import App from './App.vue'
import { pinia,usePiniaStore } from '@/stores/store'
import { pinia,usePiniaStore } from '@/stores/store'
const app = createApp(App);
usePiniaStore(app);
setup写法,配置到第三个参数,经过测试,这个写法不行,可能以后等他升级优化后就可以了吧,或者自己写一个。import { defineStore } from 'pinia'; import { ref } from 'vue'; export const useSystemDataStore = defineStore('systemdata', () => { const baseDomain = ref("http://localhost:8080/"); return { baseDomain}; }, { persist: { enabled: true, // 这个配置代表存储生效,而且是整个store都存储,默认情况下整个状态将存储在 sessionStorage 中 } } );
选项式写法
export const useSystemDataStore = defineStore('systemdata', { state: () => { return { baseDomain: "http://localhost:8080/", customerDomain: '' } }, getters: { baseDomainUserApi: (state) => state.baseDomain + 'user', }, actions: { getCustomerDomain(addStr) { this.customerDomain = this.baseDomain + addStr; }, }, persist: { enabled: true, // 这个配置代表存储生效,而且是整个store都存储,默认情况下整个状态将存储在 sessionStorage 中 } });
指定属性和存储方式
persist: { enabled: true, strategies: [ { storage: sessionStorage, paths: ['firstName', 'lastName'] }, // firstName 和 lastName字段用sessionStorage存储 { storage: localStorage, paths: ['accessToken'] }, // accessToken字段用 localstorage存储 ], },
二:
persist: { enabled: true, // 开启缓存 localstorage/sessionStorage storage: sessionStorage, // 缓存使用方式 paths:['baseDomain'] // 需要缓存键 }
整个状态将存储在 key 下的 localStorage 中user
export const useUserStore = defineStore('storeUser', { state () { return { firstName: 'S', lastName: 'L', accessToken: 'xxxxxxxxxxxxx', } }, persist: { enabled: true, strategies: [ { key: 'user', storage: localStorage, }, ], }, })
参考:https://www.cnblogs.com/fqh123/p/16515284.html
使用npm i pinia-plugin-persistedstate --save也可以实现,只是他们的配置不太一样
在自定义的store中配置
export const useSystemDataStore = defineStore('systemdata', { state: () => ({ baseDomain: "http://localhost:8080/", apiDomain: "http://localhost:29611/", title: "site title", description: "site description", current_user: { username: "jay", role: "admin", mobile: "15221098952" }, articles: [] }), getters: { getTitle: (state) => state.title + " is got!!!", }, actions: { readArticles(artName) { this.articles.push(artName); }, updateTitle(text){ this.title = text; }, updateUserName(text){ this.current_user.username = text; } }, //插件:pinia-plugin-persistedstate persist: { // 自定义数据持久化方式 key: 'xxxxxx', //指定key进行存储,此时非key的值不会持久化,刷新就会丢失 storage: window.localStorage,//localStorage//sessionStorage // paths: ['nested.data'],// 指定需要持久化的state的路径名称 beforeRestore: context => { console.log('Before' + context) }, afterRestore: context => { console.log('After' + context) }, }, //插件:pinia-plugin-persist // persist: { // enabled: true, // 这个配置代表存储生效,而且是整个store都存储,默认情况下整个状态将存储在 sessionStorage 中 // strategies: [ // { // key: 'systemdata', // storage: localStorage, // }, // ], // } });
main.js中替换对应的引入import {createPersistedState} from 'pinia-plugin-persistedstate'
修改对应的use:
pinia.use(createPersistedState({ serializer: { // 指定参数序列化器 serialize: JSON.stringify, deserialize: JSON.parse, } }));
修改自定义store中的属性的时候,要走actions,直接修改没法实现本地存储。
公共的前端代码:
<template> <div> {{msg}} <br> <ul> <li v-for="(item,index) in systemDataStore.articles" :key="index"> {{item}} </li> </ul> <br> artName:<input type="text" id="txtArtName" v-model="artName"/> <br> <button @click="readArt()">read</button> <br> <button @click="readCookie()">getCookie</button> <br> <button @click="SendHttp()">SendHttp</button> <br> <button @click="getstore()">getstore</button> <br> <button @click="updateTitle()">updateTitle</button> <br> <button @click="updateUserName()">updateUserName</button> <br> username:{{systemDataStore.current_user.username}} <br> articles:{{systemDataStore.articles}} </div> </template> <script setup> import {ref,reactive,onMounted, shallowRef, toRef, readonly, unref, isRef} from 'vue' import { useSystemDataStore } from "@/stores/index"; import {setCookie,getCookie,removeCookie} from '@/util/cookie' import service from '@/util/request' const systemDataStore = useSystemDataStore(); const SendHttp = ()=>{ service.get("/Stu/Test1").then(res=>{ console.log(res); }); } const artName = ref(systemDataStore.title); const readArt = ()=>{ debugger; // var newRefArtName = ref(unref(artName)); // systemDataStore.readArticles(newRefArtName); var newRefArtName = unref(artName); systemDataStore.readArticles(newRefArtName); } const updateTitle = ()=>{ var artNameValue = artName.value; systemDataStore.updateTitle(artNameValue); } const readCookie = ()=>{ let ck = getCookie('art'); console.log(ck) } const getstore =()=>{ console.log("title:"+systemDataStore.getTitle); } const updateUserName = ()=>{ var newRefArtName = ref(unref(artName)); systemDataStore.updateUserName(newRefArtName); } onMounted(async()=>{ }); const msg = ref('this is articles page...'); </script>