官方文档: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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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写法,配置到第三个参数,经过测试,这个写法不行,可能以后等他升级优化后就可以了吧,或者自己写一个。1 2 3 4 5 6 7 8 9 10 11 12 | 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 中 } } ); |
选项式写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 中 } }); |
指定属性和存储方式
1 2 3 4 5 6 7 | persist: { enabled: true , strategies: [ { storage: sessionStorage, paths: [ 'firstName' , 'lastName' ] }, // firstName 和 lastName字段用sessionStorage存储 { storage: localStorage, paths: [ 'accessToken' ] }, // accessToken字段用 localstorage存储 ], }, |
二:
1 2 3 4 5 | persist: { enabled: true , // 开启缓存 localstorage/sessionStorage storage: sessionStorage, // 缓存使用方式 paths:[ 'baseDomain' ] // 需要缓存键 } |
整个状态将存储在 key 下的 localStorage 中user
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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中配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 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:
1 2 3 4 5 6 | pinia.use(createPersistedState({ serializer: { // 指定参数序列化器 serialize: JSON.stringify, deserialize: JSON.parse, } })); |
修改自定义store中的属性的时候,要走actions,直接修改没法实现本地存储。
公共的前端代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | <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> |
分类:
Vue.js
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2017-09-21 打印机无法正常工作解决方法