第Ⅶ章-Ⅱ Pinia详解

ops/2024/10/18 13:46:33/

第Ⅶ章-Ⅱ Pinia详解

  • 简介
  • 安装 Pinia
  • 配置Pinia
  • 定义Store
  • 组件中使用
  • 处理异步操作
  • 模块化Store
  • 使用持久化插件

简介

Pinia 是 Vue 3 官方推荐的状态管理库,也是 Vuex 的替代方案之一。它更轻量、更现代化,并提供更好的 TypeScript 支持。

安装 Pinia

首先,确保你已经安装了Vue3 并且初始化了项目。
npm

npm install pinia

yarn

yarn add pinia

配置Pinia

在 main.ts 中创建并配置 Pinia

// src/main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';const pinia = createPinia();
const app = createApp(App);
app.use(pinia);
app.mount('#app');

定义Store

在 src/stores 目录中创建 store 文件,比如 counter.ts。

// src/stores/counter.ts
import { defineStore } from 'pinia';// 使用 TypeScript 接口定义状态类型
interface CounterState {count: number;
}// 定义 store
export const useCounterStore = defineStore({id: 'counter',state: (): CounterState => ({count: 0}),getters: {doubleCount: (state) => state.count * 2},actions: {increment() {this.count++;},decrement() {this.count--;},incrementBy(amount: number) {this.count += amount;}}
});

组件中使用

vue"><!-- src/components/CounterComponent.vue -->
<template><div><h2>Counter</h2><p>Count: {{ store.count }}</p><p>Double Count: {{ store.doubleCount }}</p><button @click="store.increment">Increment</button><button @click="store.decrement">Decrement</button><button @click="incrementBy(5)">Increment by 5</button></div>
</template><script setup lang="ts">
import { useCounterStore } from '@/stores/counter';const store = useCounterStore();const incrementBy = (amount: number) => {store.incrementBy(amount);
};
</script>

处理异步操作

// src/stores/counter.ts
import { defineStore } from 'pinia';interface CounterState {count: number;
}export const useCounterStore = defineStore({id: 'counter',state: (): CounterState => ({count: 0}),getters: {doubleCount: (state) => state.count * 2},actions: {increment() {this.count++;},decrement() {this.count--;},incrementBy(amount: number) {this.count += amount;},async incrementAsync(amount: number) {// 模拟异步操作return new Promise<void>((resolve) => {setTimeout(() => {this.incrementBy(amount);resolve();}, 1000);});}}
});

组件中使用异步操作

vue"><!-- src/components/CounterComponent.vue -->
<template><div><h2>Counter</h2><p>Count: {{ store.count }}</p><p>Double Count: {{ store.doubleCount }}</p><button @click="store.increment">Increment</button><button @click="store.decrement">Decrement</button><button @click="incrementBy(5)">Increment by 5</button><button @click="incrementAsync(3)">Increment by 3 (Async)</button></div>
</template><script setup lang="ts">
import { useCounterStore } from '@/stores/counter';const store = useCounterStore();const incrementBy = (amount: number) => {store.incrementBy(amount);
};const incrementAsync = async (amount: number) => {await store.incrementAsync(amount);
};
</script>

模块化Store

Pinia 通过 defineStore 函数实现模块化 Store,每个 Store 都是一个独立的模块。
定义用户Store

// src/stores/user.ts
import { defineStore } from 'pinia';interface UserState {name: string;age: number;
}export const useUserStore = defineStore({id: 'user',state: (): UserState => ({name: 'Alice',age: 25}),getters: {isAdult: (state) => state.age >= 18},actions: {updateName(newName: string) {this.name = newName;},incrementAge() {this.age++;}}
});

使用持久化插件

如果希望 Pinia 的状态在刷新后保持不变,可以使用 pinia-plugin-persistedstate 插件。

npm install pinia-plugin-persistedstate

配置持久化插件

// src/main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);const app = createApp(App);
app.use(pinia);
app.mount('#app');

使用持久化插件,在需要持久化的 Store 中添加 persist 选项

// src/stores/user.ts
import { defineStore } from 'pinia';interface UserState {name: string;age: number;
}export const useUserStore = defineStore({id: 'user',state: (): UserState => ({name: 'Alice',age: 25}),getters: {isAdult: (state) => state.age >= 18},actions: {updateName(newName: string) {this.name = newName;},incrementAge() {this.age++;}},persist: {enabled: true}
});

http://www.ppmy.cn/ops/37957.html

相关文章

【汇总】虚拟机网络不通(Xshell无法连接虚拟机)排查方法

搜索关键字关键字关键字&#xff1a;虚拟机虚拟机虚拟机连接失败、虚拟机无法连接、Xshell连接失败、ping baidu.com失败、静态IP设置 Kali、CentOS、远程连接 描述&#xff1a;物理机无法连接虚拟机&#xff1b;虚拟机无法访问百度&#xff0c;虚拟机无法访问baidu.com 虚拟机…

力扣经典150题第五十三题:基本计算器

目录 力扣经典150题第五十六题&#xff1a;基本计算器示例提示解题思路 力扣经典150题第五十六题&#xff1a;基本计算器 给你一个字符串表达式 s &#xff0c;请你实现一个基本计算器来计算并返回它的值。 注意:不允许使用任何将字符串作为数学表达式计算的内置函数&#xf…

黑客利用插件漏洞在 WordPress 网站上创建管理员帐户

近日&#xff0c;黑客正试图积极利用 WordPress 的 ValvePress 自动插件中的一个关键安全漏洞&#xff0c;该漏洞可能允许网站被接管。 该缺陷的编号为CVE-2024-27956&#xff0c;它影响 3.92.0 之前的所有插件版本。该问题已在 2024 年 2 月 27 日发布的3.92.1 版本中得到解决…

探索鸿蒙开发:鸿蒙系统如何引领嵌入式技术革新

嵌入式技术已经成为现代社会不可或缺的一部分。而在这个领域&#xff0c;华为凭借其自主研发的鸿蒙操作系统&#xff0c;正悄然引领着一场技术革新的浪潮。本文将探讨鸿蒙开发的特点、优势以及其对嵌入式技术发展的深远影响。 鸿蒙操作系统的特点 鸿蒙&#xff0c;作为华为推…

择偶只选丑的竟能匹配更优质配偶?让这个Python项目告诉你真相!

文章目录 引言模型核心代码讲解运行结果分析结论&#xff08;TLDR&#xff09;参考资料 引言 在一个寂寞充实的夜晚&#xff0c;我刷到了这个视频。视频大致的内容是&#xff0c;如果你不在意配偶的颜值&#xff0c;那么择偶时不妨只选丑的&#xff0c;这样你匹配到的配偶在其…

上海计算机学会2020年7月月赛C++丙组T3数根

题目描述 给定一个正整数 n&#xff0c;若 n 在十进制下的各位数字之和小于1010&#xff0c;则这个和是 n 的数根。否则&#xff0c;继续求这个和在十进制下的各位数字之和&#xff0c;直到结果小于1010为止&#xff0c;定义最后的结果为 n 的数根。 例如&#xff0c;999999 …

基于Springboot的校园健康驿站管理系统(有报告)。Javaee项目,springboot项目。

演示视频&#xff1a; 基于Springboot的校园健康驿站管理系统&#xff08;有报告&#xff09;。Javaee项目&#xff0c;springboot项目。 项目介绍&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三层体系…

LeetCode:三数之和

文章收录于LeetCode专栏 三数之和 给你一个包含n个整数的数组nums&#xff0c;判断nums中是否存在三个元素a、b、c &#xff0c;并使得a b c 0 &#xff1f;请你找出所有和为0且不重复的三元组。   注意&#xff1a;答案中不可以包含重复的三元组。   示例 1&#xff1a…