uniapp+pinia global local cache plug-in PiniaPluginUnistorage

Recently I am developing uniapp+vue3+pinia. The project needs to use the local cache function. The uni.setStorage and other methods officially provided by uniapp cannot respond dynamically. So I found the pinia-plugin-unistorage plug-in that supports uniapp pinia dynamic local persistence cache.

Insert image description here
https://github.com/dishait/pinia-plugin-unistorage

The local cache plug-in used in the previous project developed based on vite4.x vue3 pinia is pinia-plugin-persistedstate.

This plugin is the uniapp version of pinia-plugin-persistedstate .

Insert image description here

Platform compatibility

Currently compatible with vue2/3,APP/小程序/H5other platforms.

Insert image description here

Install

  • uniapp project created by cli
yarn add pinia-plugin-unistorage -D
// 或者
npm i pinia-plugin-unistorage -D
// main.js
import {
    
     createSSRApp } from 'vue'
import * as Pinia from 'pinia'
import {
    
     createUnistorage } from 'pinia-plugin-unistorage'

export function createApp() {
    
    
    const app = createSSRApp(App)

    const store = Pinia.createPinia()

    // 关键代码
    store.use(createUnistorage())

    app.use(store)

    return {
    
    
        app,
        Pinia // 此处必须将 Pinia 返回
    }
}
  • The uniapp project created by hbuilderx
    directly introduces registration after installation in the plug-in market.
// main.js
import {
    
     createSSRApp } from 'vue'
import * as Pinia from 'pinia'
import {
    
     createUnistorage } from './uni_modules/pinia-plugin-unistorage'

export function createApp() {
    
    
    const app = createSSRApp(App)

    const store = Pinia.createPinia()

    // 关键代码
    store.use(createUnistorage())

    app.use(store)

    return {
    
    
        app,
        Pinia // 此处必须将 Pinia 返回
    }
}

Quick to use

import {
    
     defineStore } from 'pinia'

export const useStore = defineStore('main', {
    
    
    state() {
    
    
        return {
    
    
            someState: 'hello pinia'
        }
    },
    unistorage: true // 开启后对 state 的数据读写都将持久化
})

vue3 setupOf course, syntax is also supported .

import {
    
     defineStore } from 'pinia'

export const useStore = defineStore(
    'main',
    () => {
    
    
        const someState = ref('hello pinia')
        return {
    
     someState }
    },
    {
    
    
        unistorage: true // 开启后对 state 的数据读写都将持久化
    }
)

At present, the plug-in does not seem to support sessionStorage. If you happen to need it in your project, you may want to take a look.

Insert image description here
Friends can also follow my public account above, where I will regularly share some front-end technical knowledge and practical project cases.

Supongo que te gusta

Origin blog.csdn.net/yanxinyun1990/article/details/131299157
Recomendado
Clasificación