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

在这里插入图片描述

需求描述

如上图所示,使用uniapp开发微信小程序商城时候,会涉及到加入到购物车模块,一般用户选择的商品加入购物车,在开发的时候可以使用pinia,将用户选择加入购物车的商品进行全局状态管理,问题在于强制刷新页面的时候,刚刚选择加入购物车的商品列表就清空了。

那么怎么解决这个问题那?

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

uniapp中使用pinia插件

1.在uniapp项目中使用pinia

要想使用插件的话,首先要在uniapp的main.js中导入pinia,HBuilder X 已内置了 Pinia,无需手动安装,下方是官方的示例代码:

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 返回
	};
}

2.安装pinia-plugin-persistedstate插件

pinia-plugin-persistedstate插件地址:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/

在项目根目录下使用命令行窗口安装插件

npm i pinia-plugin-persistedstate

安装完成,在main.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
  }
}

3.defineStore中做持久化配置

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

在defineStore函数内设置一个对象参数,persist:true便可开启持久化,当cartList数据发生改变时,在浏览器控制台的Application下Local storage中,可以找到key为“cart”的数据,如下所示:
在这里插入图片描述
如上所示,在H5开发中,使用pinia的插件再刷新的时候,购物车列表中的数据将不会消失,说明已经做了持久化的存储,但是微信小程序中是没有localstorage的,仍然不能进行持久化,下面就对persist内的storage进行设置,可以修改缓存的方式。

4.在微信小程序中做持久化存储

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的获取缓存和设置缓存的方式,在uniapp开发微信小程序中,提供了同步获取/修改缓存的API,按照如上方式的设置,在微信小程序控制台的storage中便可找到要缓存的购物车列表数据,如下图所示:
在这里插入图片描述

微信小程序可以会出现的问题

再H5中实验正常的话,在微信小程序不起作用,并且控制台会报错 TypeError: Cannot read property ‘localStorage’ of undefind

解决方法:
在这里插入图片描述
在uniapp项目中unpackage打包目录中,删除掉之前打包的mp-weixin文件,重启微信小程序项目,这样应该问题就能解决了,如果还存在问题,请在评论区留言。

### 解决方案 在微信小程序使用 `pinia-plugin-persistedstate` 插件时,出现 `store.setInputGroups is not a function` 的问题,通常与插件的初始化、上下文绑定或存储兼容性有关。以下是详细分析和解决方案。 --- #### 1. 确保 Pinia插件正确初始化 在 UniApp使用 Vue3Pinia,必须确保 Pinia 实例正确创建并挂载到应用中。以下是一个完整的初始化示例: ```typescript // main.ts import { createSSRApp } from "vue"; import { createPinia } from "pinia"; import piniaPluginPersistedstate from "pinia-plugin-persistedstate"; // 引入持久化插件 import App from "./App.vue"; const app = createSSRApp(App); const pinia = createPinia(); // 挂载持久化插件 pinia.use(piniaPluginPersistedstate); app.use(pinia); export { app }; ``` 此代码确保 Pinia 实例被正确创建,并且 `pinia-plugin-persistedstate` 插件已挂载[^2]。 --- #### 2. 替换不兼容的存储方式 微信小程序环境不支持浏览器的 `localStorage` 或 `sessionStorage`,而 `pinia-plugin-persistedstate` 默认依赖这些 API。因此需要自定义存储适配器,将数据存储到小程序的 `uni.setStorageSync` 和 `uni.getStorageSync` 中。 以下是一个适配器实现示例: ```typescript // store/persistAdapter.ts function customPersistAdapter(store: any) { const storageKey = `pinia:${store.$id}`; const storedState = uni.getStorageSync(storageKey); if (storedState) { store.$patch(storedState); // 恢复状态 } store.$subscribe((mutation, state) => { uni.setStorageSync(storageKey, state); // 持久化状态 }); } export default customPersistAdapter; ``` 然后在 Store 定义中应用该适配器: ```typescript // store/main.ts import { defineStore } from "pinia"; import customPersistAdapter from "./persistAdapter"; export const useMainStore = defineStore("main", { state: () => ({ inputGroups: [], }), actions: { setInputGroups(groups: any[]) { this.inputGroups = groups; }, }, }); const mainStore = useMainStore(); customPersistAdapter(mainStore); ``` 通过上述代码,解决了小程序环境中存储兼容性问题[^1]。 --- #### 3. 检查方法调用上下文 如果 `setInputGroups` 方法在其他模块中被调用,需确保其上下文正确绑定。可以通过以下方式修复: ```typescript // 确保方法绑定到正确的上下文 const store = useMainStore(); store.setInputGroups = store.setInputGroups.bind(store); ``` 或者,在调用时明确指定 `store` 实例: ```typescript store.setInputGroups(someGroups); ``` --- #### 4. 示例代码整合 以下是完整的解决方案示例: ```typescript // main.ts import { createSSRApp } from "vue"; import { createPinia } from "pinia"; import piniaPluginPersistedstate from "pinia-plugin-persistedstate"; import App from "./App.vue"; const app = createSSRApp(App); const pinia = createPinia(); // 挂载持久化插件 pinia.use(piniaPluginPersistedstate); app.use(pinia); export { app }; // store/persistAdapter.ts function customPersistAdapter(store: any) { const storageKey = `pinia:${store.$id}`; const storedState = uni.getStorageSync(storageKey); if (storedState) { store.$patch(storedState); } store.$subscribe((mutation, state) => { uni.setStorageSync(storageKey, state); }); } export default customPersistAdapter; // store/main.ts import { defineStore } from "pinia"; import customPersistAdapter from "./persistAdapter"; export const useMainStore = defineStore("main", { state: () => ({ inputGroups: [], }), actions: { setInputGroups(groups: any[]) { this.inputGroups = groups; }, }, }); const mainStore = useMainStore(); customPersistAdapter(mainStore); ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咸虾米_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值