当前位置: 首页 > news >正文

Uniapp安装Pinia并持久化(Vue3)

安装pinia

在uni-app的Vue3版本中,Pinia已被内置,无需额外安装即可直接使用(Vue2版本则内置了Vuex)。

  • HBuilder X项目:直接使用,无需安装。
  • CLI项目:需手动安装,执行yarn add pinia@2.0.36npm install pinia@2.0.36

编辑器环境HBuilderX4.29

安装Pinia持久化插件

npm i pinia-plugin-persistedstate

根目录下创建stores文件夹,新建index.js文件

import { createPinia } from "pinia";
// 引入持久化插件
import persist from "pinia-plugin-persistedstate";const pinia = createPinia();
// 使用持久化插件
pinia.use(persist);export default pinia;import {usetestStore
} from "./modules/test.js";// 简写
export * from "./modules/test.js";

main.js下添加挂载pinia代码

import { createSSRApp } from "vue";
import App from "./App";
import pinia from "@/stores/index.js";export function createApp() {const app = createSSRApp(App);app.use(pinia);return {app};
}

在stores目录下新建modules文件夹,在其下新建test.js测试代码

// /stores/modules/test.js
import { defineStore } from "pinia";export const usetestStore = defineStore("user", {state: () => ({name: "John Doe",age: 30}),actions: {updateName(newName) {this.name = newName;},incrementAge() {this.age++;}},persist: {storage: {// 修改存储方式getItem: uni.getStorageSync,setItem: uni.setStorageSync}}
});

image-20241106125017473

在test页面,添加如下测试代码测试效果

<template><view class="container"><text>Name: {{ user.name }}</text><text>Age: {{ user.age }}</text><button @click="incrementAge">Increment Age</button></view>
</template><script setup>import {usetestStore} from "@/stores/modules/test";// 直接使用 useUserStore 钩子函数const user = usetestStore();// 定义一个方法来增加年龄和修改姓名const incrementAge = () => {user.incrementAge();user.name = "helloWorld";};
</script>
<style lang="scss" scoped>.container {margin-top: 200rpx;}text {margin-left: 20rpx;}
</style>

启动运行后查看微信小程序test页面,可以看到pinia已经持久化保存到缓存里

image-20241106125530420

http://www.lryc.cn/news/479242.html

相关文章:

  • 基于Dpabi和spm12的脑脊液(csf)分割和提取笔记
  • 【每日一题】2012考研数据结构 - 求字符串链表公共后缀
  • 数据结构和算法-贪心算法01- 认识贪心
  • Bash Shell - 获取日期、时间
  • runnable和callable区别和底层原理
  • Springboot 整合 Java DL4J 打造自然语言处理之语音识别系统
  • 虚幻引擎5(UE5)学习教程
  • 从0开始深度学习(26)——汇聚层/池化层
  • 兼职发薪系统:高效、便捷的劳务发薪解决方案
  • MySQL数据库单表查询习题
  • 多模态PaliGemma——Google推出的基于SigLIP和Gemma的视觉语言模型
  • 电路原理:电阻桥。
  • 实践出真知:MVEL表达式中for循环的坑
  • Flutter运行App时出现“Running Gradle task ‘assembleDebug“问题解决
  • 基于SSM(Spring + Spring MVC + MyBatis)框架的咖啡馆管理系统
  • 【SpringBoot】18 上传文件到数据库(Thymeleaf + MySQL)
  • 计算机体系结构之系统吞吐量(三)
  • 高级 HarmonyOS主题课—— 帮助快速构建各种文本识别应用的课后习题
  • windows C#-异常和异常处理概述
  • 每日一题——第一百二十四题
  • 在 CentOS 7 上设置 OpenResty 开机启动
  • 势不可挡 创新引领 | 生信科技SOLIDWORKS 2025新品发布会·苏州站精彩回顾
  • 数仓之全量表、增量表、快照表、切片表、拉链表的基本概念
  • 【富集分析GSEA】如何理解富集分析以及应用
  • 一七五、HTML 不同类型的事件及其说明和示例
  • 数量少的连锁店要不要用智能巡检?
  • 【CSS】外边距塌陷
  • WPF MVVM入门系列教程(二、依赖属性)
  • Springboot集成syslog+logstash收集日志到ES
  • Devops业务价值流:软件研发最佳实践