【UniApp】-uni-app-pinia存储数据

发布时间 2023-12-19 09:27:41作者: BNTang

前言

  • 经过上个章节的介绍,大家可以了解到 uni-app-数据缓存 的基本使用方法
  • 那本章节来给大家介绍一下 uni-app-pinia存储数据 的基本使用方法
  • 经过我这么多篇章的介绍,我发现大家环境比较耗时,所以在今后的文章中,我会尽量减少环境的搭建
  • 如果某一篇的文章环境确实是不一样的,我会在文章中说明,然后编写对应的搭建过程

本文的由来呢,就是因为在 Vue2 中与 Vue3 中都可以使用 Vuex 来进行数据的存储, 但是在 Vue3 出现了 Pinia,所以我就想着在 uni-app 中使用 Pinia 来进行数据的存储。

步入正题

首先来给大家看看官方文档吧,在文档中找到, uni-app -> 教程 -> vue语法,先来看 Vue2:

可以从图中看到,在 Vue2 当中的存储方式只有 Vuex,然后再来看看 Vue3:

多了一个 Pinia,好,知道了这些内容之后我就来开始写代码编写示例,带大家过一遍。

  • 使用 UniApp 创建的项目是内置了 Pinia,Vue2 项目暂不支持

根据官方文档的介绍,首先我们需要搭建一个对应的目录结构:

├── pages
├── static
└── stores
    └── counter.js
├── App.vue
├── main.js
├── manifest.json
├── pages.json
└── uni.scss

就是创建一个 stores 文件夹,在该文件夹下创建对应模块的 js 文件。

  • 创建一个默认模板项目,基于 Vue3
  • 创建好项目之后,首先更改 main.js,导入 pinia,注册 pinia,导出 pinia

Pinia

配置 Pinia

导入 Pinia:

import * as Pinia from 'pinia';

注册 Pinia:

app.use(Pinia.createPinia());

导出 Pinia:

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

使用 Pinia

首先在 stores 文件夹下,创建 counter.js,内容如下:

import {
	defineStore
} from 'pinia';

export const useCounterStore = defineStore('counter', {
	state: () => {
		return {
			count: 0
		};
	},
	// 也可以这样定义
	// state: () => ({ count: 0 })
	actions: {
		increment() {
			this.count++;
		},
		decrement() {
			this.count--;
		},
	},
});

如上代码通过 defineStore 定义了一个名为 counter 的 store,然后通过 state 定义了一个 count 的状态,然后通过 actions 定义了两个方法,分别是 increment 和 decrement,分别用来增加和减少 count 的值。

再接着在首页页面,添加两个按钮分别是增加与减少调用 store 中的方法:

<template>
	<view>
		{{ count }}
		<button type="primary" @click="myIncrement">增加</button>
		<button type="primary" @click="myDecrement">减少</button>
	</view>
</template>

<script setup>
	import {
		useCounterStore
	} from '@/stores/counter.js'
	import {
		storeToRefs
	} from 'pinia'

	const counterStore = useCounterStore()

	const {
		count
	} = storeToRefs(counterStore)

	function myIncrement() {
		counterStore.increment()
	}

	function myDecrement() {
		counterStore.decrement()
	}
</script>

代码我写完了,先来看运行的效果,然后我在一一解释代码:

  • 如上代码的含义首先在 script setup 中导入了 useCounterStore,然后通过 useCounterStore 创建了一个 counterStore
  • 然后通过 storeToRefs 将 counterStore 中的 count 转换成了 ref,然后在模板中通过 {{ count }} 将 count 的值显示出来
  • 然后通过 @click 调用 myIncrement 和 myDecrement 方法,然后在 myIncrement 和 myDecrement 方法中调用了 counterStore 中的 increment 和 decrement 方法
  • 然后通过 counterStore.increment() 和 counterStore.decrement() 调用了 store 中的方法

好,到这已经结束了,是不是很简单,我就不多说了,大家可以自己去尝试一下。

这个存储的是全局的数据,大家还可以新建一个 one 页面,配置一下 tabBar 在 one 页面中从 store 中获取 count 的值, 显示一下即可,在首页操作之后 one 页面的 count 的值也会发生变化。

End

  • 如果你有任何问题或建议,欢迎在下方留言,我会尽快回复
  • 如果你觉得本文对你有帮助,欢迎点赞、收藏,你的支持是我写作的最大动力