【uniapp】状态存储Pinia的使用,以及它的数据持久化

一、uni-app 使用Pinia

uni-app创建的Vue3版本已经内置了pinia,不需要安装即可使用(Vue2版本内置了Vuex

  • 使用 HBuilder X 创建的项目,不需要手动安装,直接使用即可。
  • 使用 CLI 需要手动安装,执行 yarn add pinia@2.0.33 npm install pinia@2.0.33

二、Pinia的模块化持久化

2.1. 文件目录如下

在这里插入图片描述

2.2. 安装Pinia持久化插件

npm i pinia-plugin-persistedstate

2.3. counter.js

import {
	defineStore
} from 'pinia'
import {
	ref
} from 'vue'
export const useCounterStore = defineStore('counter', () => {
	const count = ref(0)

	function increment() {
		count.value++
	}

	return {
		count,
		increment
	}
}, {
	persist: {
		storage: {
			getItem: uni.getStorageSync,
			setItem: uni.setStorageSync
		}
	}
})

2.3. user.js同counter.js,这里忽略

2.5. index.js

import {
	createPinia
} from 'pinia'
// 引入持久化插件
import persist from 'pinia-plugin-persistedstate'

const pinia = createPinia()
// 使用持久化插件
pinia.use(persist)

export default pinia

// import { useUserStore } from '@/store/modules/user.js'
// export { useUserStore }
// import { useCounterStore } from '@/store/modules/counter.js'
// export { useCounterStore }

// 简写
export * from './modules/user.js'
export * from './modules/counter.js'

2.6. 并且在main.js中引入

import App from './App'

// #ifdef VUE3
import {
	createSSRApp
} from 'vue'
// 引入pinia(uniapp的Vue3版本自带pinia,Vue2版本自带Vuex)
import pinia from '@/store/index'
export function createApp() {
	const app = createSSRApp(App)
	// 注入全局方法
	app.provide('$px2rem', px2rem)
	// 注入pinia
	app.use(pinia)
	return {
		app
	}
}
// #endif

三、使用

这里以counter模块使用为例

<template>
	<view class="content">
		<button @click="increment">点我+1</button>
		<text class="title">{{count}}</text>
	</view>
</template>

<script setup>
    // 所有的模块已经统一在index.js导出
	import {
		useCounterStore
	} from '@/store/index.js'
	import {
		storeToRefs
	} from 'pinia'
	const store = useCounterStore()
	// `name``doubleCount` 是响应式的 ref
	// 同时通过插件添加的属性也会被提取为 ref
	// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
	const {
		count
	} = storeToRefs(store)
	// 作为 action 的 increment 可以直接解构
	const {
		increment
	} = store
</script>




<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}	
	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
  • 11
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值