序:
1、博主vue3、ts 5.x、pinia 2.1.3版本,
2、所以如果试了不行的你看看是不是自己版本和博主的对不上
3、其实就是省略掉localStorage 这一步,会自己写的小伙伴自己写个也是蛮快的
4、放个中文文档==》Home | pinia-plugin-persistedstate
5、压缩localStorage 要存的数据,我记得每个浏览器对localStorage 的存储是有限制大小的有的1M 有的6M。哪天你纯localStorage 发现没效果,或者丢失,你都不知道什么问题导致的。
一、安装依赖
1、依赖
cnpm i pinia-plugin-persistedstate -S
2、 main.ts
import pinia from '@/stores'
app.use(pinia)
3、stores/index.ts
import { ref, computed } from 'vue'
import { createPinia,defineStore } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
export const useCounterStore = defineStore('counter', () => {
const i=ref<number>(0);
const edit=(val:number)=>{
i.value=val;
}
const newi=computed(():number=>{
return i.value;
})
// const edit=
return{
i,
newi,
edit
}
},{persist: true});
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
export default pinia;
4、 index.vue 调用
<template>
<div class="login">
<!-- {{thisVal}}
<input type="text" v-model="textVal">
<a href="#" @click.prevent="jump">跳</a> -->
</div>
</template>
<script setup lang="ts" >
import {ref, toRefs, watch} from "vue"
import {useCounterStore} from "@/stores";
const {i,newi} = toRefs(useCounterStore())
const {edit} = useCounterStore()
edit(2)
console.log(newi.value)
console.log(i.value);
//如果你不喜欢解耦,也可以写成下面
console.log(useCounterStore().i)
useCounterStore().edit(3)
console.log(useCounterStore().i)
</script>
<style>
</style>
二、demo案例
1、这个是两个变量(别在乎细节,我纯为了演示和好理解)
他是存在一个key里面的!没办法出
store.ts
import { ref, computed } from 'vue'
import { createPinia,defineStore } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
export const useCounterStore = defineStore('counter', () => {
const i=ref<number>(0);
const b=ref<string|null>(null);
const edit=(val:number)=>{
i.value=val;
}
const newi=computed(():number=>{
return i.value;
})
const edit1=(val:string)=>{
b.value=val;
}
const newi1=computed(():(string|null)=>{
return b.value;
})
// const edit=
return{
i,
newi,
edit,
b,
newi1,
edit1,
}
},{persist: true});
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
export default pinia;
index.vue
<template>
<div class="login">
<!-- {{thisVal}}
<input type="text" v-model="textVal">
<a href="#" @click.prevent="jump">跳</a> -->
</div>
</template>
<script setup lang="ts" >
// import {ref, toRefs, watch} from "vue"
import {useCounterStore} from "@/stores";
const store=useCounterStore()
//如果你不喜欢解耦,也可以写成下面
console.log(store.i)
useCounterStore().edit(3)
console.log(store.i)
//如果你不喜欢解耦,也可以写成下面
console.log(store.b)
useCounterStore().edit1("xxx")
console.log(store.b)
</script>
<style>
</style>
好,我们认下接下去要改变存储的变量key
key: 'cyc'
三、压缩加密
序那边博主开头说了,每个浏览器对localStorage 是有限制大小的,你不压缩,有时候你触发了某个bug,你都不知道怎么回事,来,跟着博主操作
1、安装依赖
cnpm install zipson -S
2、配置stores/index.ts
serializer: {
deserialize: parse,
serialize: stringify,
},
3、运行