在學習uniapp過程中,看到了pinia-plugin-persist-uni插件,以前面試過程中也有面試過說vuex數據刷新之前的數據就丟失了,之前回答的是把數據存儲到數據庫或者本地存儲。pinia-plugin-persist-uni本質上數據也是本地存儲。
1、安裝
? npm install?pinia-plugin-persist-uni
2、使用
main.ts
import piniaPersist from 'pinia-plugin-persist-uni'
?const app = createApp(App)
const pinia = createPinia()
pinia.use(piniaPersist)
app.use(pinia)
store文件
寫法一:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter',()=>{
? const counter = ref(0)
? const doubleCount = computed(()=>counter.value*2)
? const increment = ()=>{
? ? counter.value++
? }
? return {
? ? counter,
? ? doubleCount,
? ? increment,
? ?
? }
},{
? persist: {
? ? enabled: true,
? ? strategies: [
? ? ? {
? ? ? ? key: 'aaa', // 存儲的鍵名
? ? ? ? storage: localStorage, // 存儲方式,可以是 localStorage 或 sessionStorage
? ? ? },
? ? ],
? },
})
寫法二
export const useCounterStore = defineStore('counter', {
? state: () => ({
? ? counter: 0,
? }),
? getters: {
? ? doubleCount: (state) => state.counter * 2,
? },
? actions: {
? ? increment() {
? ? ? this.counter++
? ? },
? },
? persist: {
? ? enabled: true,
? ? strategies: [
? ? ? {
? ? ? ? key: 'counter', // 存儲的鍵名
? ? ? ? storage: localStorage, // 存儲方式,可以是 localStorage 或 sessionStorage
? ? ? },
? ? ],
? }
})
效果:
?