uniapp Vue3版本,用pinia存储持久化插件pinia-plugin-persistedstate对微信小程序的配置

刷新后,数据不见了。

Pinia插件pinia-plugin-persistedstate可配置的 Pinia 存储持久化。

uniapp中使用pinia插件

HBuilder X 已内置了 Pinia,无需手动安装。

在uniapp的main.js中导入pinia即可,代码如下:

js 复制代码
import App from './App'
import { createSSRApp } from 'vue';
import * as Pinia from 'pinia';

export function createApp() {
	const app = createSSRApp(App);
	app.use(Pinia.createPinia());
	return {
		app,
		Pinia, // 此处必须将 Pinia 返回
	};
}

在项目根目录下使用命令行窗口安装插件:npm i pinia-plugin-persistedstate

main.js导入插件,修改官方示例代码,如下所示:

js 复制代码
import { createSSRApp } from 'vue'
import * as Pinia from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
export function createApp() {
  const app = createSSRApp(App)
  const pinia = Pinia.createPinia()
  pinia.use(piniaPluginPersistedstate)
  app.use(pinia);
  return {
    app,
    Pinia
  }
}

在defineStore函数内设置一个对象参数,persist:true便可开启持久化,然后代码这样写:

js 复制代码
export const useCartStore = defineStore('cart', () => {	
    const goodsTotal = computed(()=>{
        ...实现代码
    })	
    const priceTotal = computed(()=>{
        ...实现代码
    })	
    const pushGoods = (data)=>{
        ...实现代码
    }
    return {
        cartList,
        pushGoods,
        goodsTotal,
        priceTotal
    }
},{
    persist:true
});

h5,就是存localstorage的。

微信小程序没有localsotrage,所以对persist内的storage进行设置。

js 复制代码
export const useCartStore = defineStore('cart', () => {	
    const goodsTotal = computed(()=>{
        ...实现代码
    })	
    const priceTotal = computed(()=>{
        ...实现代码
    })	
    const pushGoods = (data)=>{
        ...实现代码
    }
    return {
        cartList,
        pushGoods,
        goodsTotal,
        priceTotal
    }
},{
    persist:{
        storage:{
            getItem:uni.getStorageSync,
            setItem:uni.setStorageSync			
        }
    }
});

在微信小程序控制台的storage中便可找到要缓存的数据。

微信小程序可能会出现的问题 在H5中实验正常的话,在微信小程序不起作用,并且控制台会报错 TypeError: Cannot read property 'localStorage' of undefind

在uniapp项目中unpackage打包目录中,删除掉之前打包的mp-weixin文件,重启微信小程序项目,这样应该问题就能解决了。

相关推荐
奋斗吧程序媛12 分钟前
vue3 Study(1)
前端·javascript·vue.js
@Autowire15 分钟前
Layout-position
前端·css
QQ129584550416 分钟前
ThingsBoard - APP首页修改为手工选择组织
前端·javascript·物联网·iot
whyfail17 分钟前
前端数据存储新选择:IndexedDB与Dexie.js技术指南
前端·javascript·数据库
椰果uu18 分钟前
vue-virtual-scroller-虚拟滚动列表:渲染不定高度长列表+可控跳转
前端·javascript·typescript·vue
Kagol25 分钟前
深入浅出 TinyEditor 富文本编辑器系列之一:TinyEditor 是什么
前端·typescript·开源
空城雀29 分钟前
python精通连续剧第一集:简单计算器
服务器·前端·python
不务正业的前端学徒41 分钟前
手写简单的call bind apply
前端
jump_jump44 分钟前
Ripple:一个现代的响应式 UI 框架
前端·javascript·前端框架
用户904706683571 小时前
Nuxt css 如何写?
前端