【Vue全家桶】Pinia状态管理

news/2025/3/14 16:51:15/

【Vue全家桶】Pinia状态管理

文章目录

  • 【Vue全家桶】Pinia状态管理
  • 写在前面
  • 一、认识Pinia
    • 1.1 认识Pinia
    • 1.2 为什么使用Pinia?
  • 二、 Store
    • 2.1 定义Store
    • 2.2 Option对象
    • 2.3 setup函数
    • 2.4 使用定义的Store
  • 三、Pinia核心概念State
    • 3.1 定义State
    • 3.2 操作State
    • 3.3 使用选项式 API 的用法
  • 四、Pinia核心概念Getters
    • 4.1 认识Getters
    • 4.2 访问Getters
    • 4.3 向Getters传递参数
  • 五、Pinia核心概念Actions
    • 5.1 认识Actions
    • 5.2 Actions执行异步操作
    • 5.3 访问其他 store 的 Actions

写在前面

🤗这里是前端程序员小张!

🌻人海茫茫,感谢这一秒你看到这里。希望我的文章对你的有所帮助!

🌟愿你在未来的日子,保持热爱,奔赴山海!

一、认识Pinia

1.1 认识Pinia

  • Pinia开始于大概2019年,其目的是设计一个拥有 组合式 API 的 Vue 状态管理库
  • 目前同时兼容Vue2、Vue3,也并不要求你使用Composition API
  • Pinia本质上依然是一个状态管理库,用于跨组件、页面进行状态共享

状态管理库是什么

  • 是一个保存状态和业务逻辑的实体,它会持有为绑定到你组件树的状态和业务逻辑,也就是保存了全局的状态
  • 它有点像一个永远存在的组件,每个组件都可以读取和写入它;
  • 你可以在你的应用程序中定义任意数量的Store来管理你的状态;

应该在什么时候使用 Store?

  • 一个 Store 应该包含可以在整个应用中访问的数据这包括在许多地方使用的数据,例如显示在导航栏中的用户信息,以及需要通过页面保存的数据,例如一个非常复杂的多步骤表单。
  • 另一方面,应该避免在 Store 中引入那些原本可以在组件中保存的本地数据,例如,一个元素在页面中的可见性。

安装npm install pinia

在这里插入图片描述

1.2 为什么使用Pinia?

使用 Pinia,即使在小型单页应用中,你也可以获得如下功能:

  • Devtools 支持
    • 追踪 actions、mutations 的时间线
    • 在组件中展示它们所用到的 Store
    • 让调试更容易的 Time travel
  • 热更新
    • 不必重载页面即可修改 Store
    • 开发时可保持当前的 State
  • 插件:可通过插件扩展 Pinia 功能
  • 为 JS 开发者提供适当的 TypeScript 支持以及自动补全功能。
  • 支持服务端渲染

二、 Store

Store有三个核心概念:

  • state、getters、actions;
  • 等同于组件的data、computed、methods;
  • 一旦 store 被实例化,你就可以直接在 store 上访问 state、getters 和 actions 中定义的任何属性;

2.1 定义Store

Store 是用 defineStore() 定义的

  • 它需要一个唯一名称,作为第一个参数传递
  • 这个名字 ,也被用作 id ,是必须传入的, Pinia 将用它来连接 store 和 devtools。
  • 返回的函数统一使用useX作为命名方案,这是约定的规范
  • defineStore() 的第二个参数可接受两类值:Setup 函数或 Option 对象
import { defineStore } from 'pinia'// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useCounterStore = defineStore('counter', {// 其他配置...
})

2.2 Option对象

我们也可以传入一个带有 stateactionsgetters 属性的 Option 对象:

  • 我们可以认为
    • state 是 store 的数据 (data)
    • getters 是 store 的计算属性 (computed)
    • actions 则是方法 (methods)
export const useCounterStore = defineStore('counter', {state: () => ({ count: 0 }),getters: {double: (state) => state.count * 2,},actions: {increment() {this.count++},},
})

2.3 setup函数

与 Vue 组合式 API 的 setup 函数 相似

  • 我们可以传入一个函数,该函数定义了一些响应式属性和方法
  • 并且返回一个带有我们想暴露出去的属性和方法的对象
  • Setup Store 中:
    • ref() 就是 state 属性
    • computed() 就是 getters
    • function() 就是 actions
export const useCounterStore = defineStore('counter', () => {const count = ref(0)function increment() {count.value++}return { count, increment }
})

2.4 使用定义的Store

Store在它被使用之前是不会创建的,我们可以通过调用**useStore()**来使用Store:

<script setup>
import { useCounterStore } from '@/stores/counter'
const store = useCounterStore()
</script>
  • 一旦 store 被实例化,你可以直接访问在 store 的 stategettersactions 中定义的任何属性。
  • 注意Store获取到后不能被解构,那么会失去响应式
    • 为了从 Store 中提取属性同时保持其响应式,您需要使用storeToRefs()

三、Pinia核心概念State

3.1 定义State

state 是 store 的核心部分,因为store是用来帮助我们管理状态的

  • 在 Pinia 中,状态被定义为返回初始状态的函数
import { defineStore } from 'pinia'export const useCounter = defineStore('counter', {// 为了完整类型推理,推荐使用箭头函数state: () => {return {// 所有这些属性都将自动推断出它们的类型counter: 0}}
})

3.2 操作State

读取和写入State

  • 默认情况下,您可以通过 store 实例访问状态来直接读取和写入状态
const counterStore = useCounter()
counterStore.counter++

重置State

  • 你可以通过调用 store 上的 $reset() 方法将状态 重置 到其初始值
const counterStore = useCounter()
counterStore.$reset()

变更State

  • 除了用 store.count++ 直接改变 store,你还可以调用 $patch 方法
  • 它允许你用一个 state 的对象在同一时间更改多个属性
counterStore.$patch({counter : 1,age: 120,name: 'pack',
})

3.3 使用选项式 API 的用法

// 示例文件路径:
// ./src/stores/counter.jsimport { defineStore } from 'pinia'const useCounterStore = defineStore('counter', {state: () => ({count: 0,}),
})

四、Pinia核心概念Getters

4.1 认识Getters

Getters 完全等同于 store 的 state 的计算属性

  • 可以通过 defineStore() 中的 getters 属性来定义它们。
  • 推荐使用箭头函数,并且它将接收 state 作为第一个参数
export const useCounter = defineStore('counter', {state: () => ({counter: 15}),getters: {doubleCounter: (state) => state.counter * 2}
})

4.2 访问Getters

访问当前store 实例上的 getters

const counterStore = useCounter()
console.log(counterStore.doubleCounter)

Getters中访问当前store实例的其他Getters

  • 我们可以通过 this,你可以访问到其他任何 getters
getters: {doubleCount: (state) => state.counter * 2,// 返回 counter 的值乘以 2 加 1doubleCountPlusOne() {return this.doubleCount + 1}
}

访问其他store实例的Getters

getters: {otherGetter(state) {const otherStore = useOtherStore()return state.localData + otherStore.data}
}

4.3 向Getters传递参数

Getters可以 返回一个函数,该函数可以接受任意参数

export const useUserListStore = defineStore('main', {state: () => ({users: [{ id: 1, name: 'lisa' },{ id: 2, name: 'pack' }]}),getters: {getUserById: (state) => {return (userId) => {state.users.find((user) => user.id === userId)}}}
})

在组件中使用:

<template><p>User 2: {{ getUserById(2) }}</p>
</template><script setup>
import { useUserListStore } from './store'
const userList = useUserListStore()
const { getUserById } = storeToRefs(userList)
</script>

五、Pinia核心概念Actions

5.1 认识Actions

Actions 相当于组件中的 methods。

  • 可以通过 defineStore() 中的 actions 属性来定义,并且它们也是定义业务逻辑的完美选择。

  • 类似 Getters,Actions 也可通过 this 访问整个 store 实例

    export const useCounterStore = defineStore('counter', {state: () => ({counter: 15}),actions: {increment() {this.counter++}}
    })
    

5.2 Actions执行异步操作

Actions 中是支持异步操作的,并且我们可以编写异步函数,在函数中使用await

actions: {increment() {this.counter++},async fetchDataAction() {const res = await fetch("http://jsonplaceholder.typicode.com/posts")const data = await res.json()return data}
}

Actions 可以像函数或者通常意义上的方法一样被调用:

<script setup>
import { useCounterStore } from './store/couter';const counterStore = useCounterStore()
counterStore.fetchDataAction().then(res => {console.log(res)
})
</script>

5.3 访问其他 store 的 Actions

import { useAuthStore } from './auth-store'export const useSettingsStore = defineStore('settings', {state: () => ({preferences: null,// ...}),actions: {async fetchUserPreferences() {const auth = useAuthStore()if (auth.isAuthenticated) {this.preferences = await fetchPreferences()} else {throw new Error('User must be authenticated')}},},
})

http://www.ppmy.cn/news/48095.html

相关文章

为何MySQL 8.0开始取消了查询缓存

官方文档说明&#xff1a;MySQL :: MySQL 8.0: Retiring Support for the Query Cache MySQL查询缓存是查询结果缓存。它将以SEL开头的查询与哈希表进行比较&#xff0c;如果匹配&#xff0c;则返回上一次查询的结果。 进行匹配时&#xff0c;查询必须逐字节匹配&#xff0c;例…

Android:usb转232串口通信

准备工作 首先得adb进入盒子root模式&#xff0c;将/dev/ttys1这个文件改为777&#xff0c;使得所有用户可操作 adb root adb remount adb shell 进入设备的root模式&#xff0c;执行 chmod 777 /dev/ttys1 执行完成后退出 exit 再执行 adb shell chmod 666 /dev/ttyS1 如…

比较运算符、关键字子查询MySQL数据库 (头歌实践教学平台)

文章目的初衷是希望学习笔记分享给更多的伙伴&#xff0c;并无盈利目的&#xff0c;尊重版权&#xff0c;如有侵犯&#xff0c;请官方工作人员联系博主谢谢。 目录 第1关&#xff1a;带比较运算符的子查询 任务描述 相关知识 子查询 带比较运算符的子查询 编程要求 第2关…

第二章 法的内容与形式

目录 第一节 法的内容与形式的概念 一、法的内容与形式的含义 二、法的内容和形式的关系 第二节 法律权利与法律义务 一、权利和义务的概念 二、权利和义务的分类 三、权利与义务的联系 第三节 法的成文形式与不成文形式 一、历史上各种法的表现形式 二、成文法与不成文…

Vue中组件传值

Vue官网链接-向子组件传递数据 Vue官网-Prop 父组件将值传递给子组件 父组件中的值可以通过v-bind与子组件中的props属性将值传递给子组件&#xff0c;也可以通过v-on与this.$emit()间接被子组件中的函数调用 1、使用v-bind将父组件中data中的键与子组件中的props键进行绑定 …

【SpringBoot】一:SpringBoot的基础(下)

文章目录 1.外部化的配置1.1 配置文件基础1.1.1 配置文件格式1.1.2 application文件1.1.3 application.properties1.1.4 application.yml1.1.5 environment1.1.6 组织多文件1.1.7多环境配置 1.2 绑定Bean1.2.1 简单的属性绑定1.2.2 嵌套Bean1.2.3 扫描注解1.2.4 处理第三方库对…

Vue中mixins(混入)的介绍和使用

什么是Mixin&#xff1f; 想要使用一个事物或者工具&#xff0c;我们首要先了解它是什么&#xff0c;这样我们才好对症下药。 其实Mixin不是Vue专属的&#xff0c;可以说它是一种思想&#xff0c;也可以说它就是混入的意思&#xff0c;在很多开发框架中都实现了Mixin(混入)&a…

异常(throwable)

异常 异常分类 &#xff08;1&#xff09;Throwable类 所有的异常类型都是它的子类&#xff0c;它派生两个子类Error、Exception。 &#xff08;2&#xff09;Error类 表示仅靠程序本身无法恢复的严重错误&#xff08;内存溢出动态链接失败、虚拟机错误&#xff09;&#…