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.
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 .
Platform compatibility
Currently compatible with vue2/3,APP/小程序/H5
other platforms.
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 setup
Of 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.
Friends can also follow my public account above, where I will regularly share some front-end technical knowledge and practical project cases.