《Vue3 基础知识》Pinia 01 之 基础

2024-06-15 05:36

本文主要是介绍《Vue3 基础知识》Pinia 01 之 基础,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Pinia 基础知识

前言

说明

  • 本篇更倾向于 选项式 API 写法,因为项目是从 Vue2 升级至 Vue3,为更好且快速适配;
  • Vue2 中,Vuex3Pinia 不能一起使用。因为 Pinia 使用的是 Vuex3 现有接口;
  • Vue3 中,Vuex4Pinia 可以一起使用;

与 Vuex 的差异

  • 参考 从 Vuex ≤4 迁移;
  • Pinia 废弃 mutation

Store/Pinia 是什么

  • 承载着全局状态;
  • 一个保存状态和业务逻辑的实体,它并不与你的组件树绑定;
  • 可理解为一个永远存在的组件,每个组件都可以读取和写入它;
  • 三个概念:state, getter, action ,可理解为组件中的 data, computed, methods
  • store 是一个用 reactive 包装的对象,不用在 getter 后面写 .value
  • store 不能解构,否则失去响应性。使用 storeToRefs() 解构可保持响应性;
<script setup>
import { storeToRefs } from 'pinia'const store useCounterStore()const { name, doubleCount } = storeToRefs(store)
</script>

核心概念

定义 Store

  • 使用 defineStore 定义,变量名建议以 use 开头且以 Store 结尾,例如:useUserStore
  • 第一个参数要求 独一无二 ,且必传。它用来连接 store 和 devtools;
  • 第二个参数可接受两种类值:Setup 函数或 Option 对象。具体参考此处;
import { defineStore } from 'pinia'export const useUserStore = defineStore('user', {// ...
})

State

  • statestore 的核心;
  • state 被定义为一个返回初始化状态的函数。使得其可同步支持服务端和客户端(不理解…);
  • 为了完整类型推理,推荐使用箭头函数;
// 选项式API方式
import { defineStore } from 'pinia'const userUserStore = defineStore('user', {// 使用箭头函数state: ()=> {return {name: 'admin',age: 30,}}
})

使用

通过实例访问,直接读写;

const store = userUserStore();store.name

重置 state

选项式 API 直接调 $reset() 方法。组合式API 要自己创建,参考此处。

const store = userUserStore();store.$reset()

只读的计算属性

使用 mapState() 辅助函数将 state 映射为只读的计算属性。

import { mapState } from 'pinia'
import { useUserStore } from '../stores/user'export default {computed: {// 直接用 this.name,与 store.name 数据相同...mapState(useUserStore, ['name']),...mapState(useUserStore, {// 与上述相同,但注册为 this.myNamemyName: 'name',// 也可以用函数fullName: store => store.name + 'Liu',// 可以访问 this,但没标注类型UserString(store) {return store.age + this.fullName}})}
}

可修改的计算属性

使用 mapWritableState() 辅助函数,但不能像 mapState() 传递成一个函数

import { mapWritableState } from 'pinia'
import { useUserStore } from '../stores/user'export default {computed: {// 直接用 this.name,与 store.name 数据相同。且能改变 this.name = '123'...mapWritableState(useUserStore, ['name']),...mapWritableState(useUserStore, {// 与上述相同,但注册为 this.myName。但没有函数方式myName: 'name',})}}

变更 state

  • 使用 $patch ,两种方式:对象方式和函数方式;
  • 区别是 p a t c h ( ) 允许你将多个变更归入 d e v t o o l s 的同一个条目中。同时请注意,直接修改 s t a t e , patch() 允许你将多个变更归入 devtools 的同一个条目中。同时请注意,直接修改 state, patch()允许你将多个变更归入devtools的同一个条目中。同时请注意,直接修改statepatch() 也会出现在 devtools 中,而且可以进行 time travel (在 Vue 3 中还没有)。不理解…
// 方式一:对象方式
store.$patch({count: store.count + 1,age: 120,name: 'DIO',
})// 方式二:函数方式
store.$patch((state) => {state.items.push({ name: 'shoes', quantity: 1 })state.hasChanged = true
})

替换 state

// 这实际上并没有替换`$state`
store.$state = { count: 24 }
// 在它内部调用 `$patch()`:
store.$patch({ count: 24 })

Getter

  • 完全等同于 store 的 state 计算值,使用 getters 属性来定义;
  • 推荐使用箭头函数,并将接收 state 作为第一个参数;
  • 通过 this 访问 store 实例或其它 getter 值;
// 定义
export const useCounterStore = defineStore('counter', {state:() {return {count: 0,}},getters: {// 通过第一个参数 state 访问 countdoubleCount(state) {return state.count * 2},// 通过 this 访问其它 getter 值doublePlusOne() {return this.doubleCount + 1}}
})
// 访问
<script setup>
import { useCounterStore } from './counterStore'const store = useCounterStore()
</script>
<template><p>Double count is {{ store.doubleCount }}</p>
</template>
  • 向 getter 传递参数,getter 是幕后的计算属性,所以不可以向它们传递任务参数。但可以返回一个函数,函数可接受任意参数;
export const useUserListStore = defineStore('userList', {getters: {getUserById(state) {return (useId) => state.userd.find((user) => user.id === userId)}}
})
  • 想要使用另一个 store 的 getter,直接在 getter 内使用即可;
import { useOtherStore } from './other-store'export const useStore = defineStore('main', {state:() => {//...},getters: {otherGetter(state) {const otherStore = useOtherStore()return state.localData + otherStore.data}}
})
  • setup 中使用,直接访问就行,与 state 属性完全一样;
<script setup>
const store = useCounterStore()
store.count = 3
store.doubleCount // 6
</script>
  • 使用 mapState() 函数将其映射为 getters,与 state 用法一致;

Action

  • 相对于组件中的 method,可通过 defineStore() 中的 actions 属性定义;
  • 它们也是定义业务逻辑的完美选择;
  • 类似 getter,action 也可通过 this 访问整个 store 实例;
  • 不同之处,action 可以是异步的,可使用 async 或 Promise;
import { mande } from 'mande'const api = mande('/api/users')export const useUsers = defineStore('users', {state: () => {return {userData: null,}},actions: {async registerUser(login, password) {try {this.userData = await api.post({login, password})} catch(error) {showTooltip(error)}}}
})

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

<script setup>
const store = useCounterStore();
// 将 action 作为 store 的方法进行调用
store.randomizeCounter()
</script>
<template><!-- 即使在模板中也可以 --><button @click="store.randomizeCounter()"></button>
</template>
  • 访问其它 store 的 action,直接在 action 中调就好了;

  • 选项式API的用法

import { defineStore } from 'pinia'const userCounterStore = defineStore('counter', {state: () => {count: 0},actions: {increment() {this.count++;}}
})
  • 使用 setup();
  • 不使用 setup():mapActions 辅助函数将action属性映射为你组件中的方法;

组件外的 Store

单页面应用
  • app.use(pinia) 安装后,对 useStore() 的调用才能正常使用;
  • 为确保 pinia 实例被激活,最简单的方法是将 useStore() 调用放在 pinia 安装之后再执行的函数中;
import { useUserStore } from '@/stores/user'
import { createApp } from 'vue'
import App from './App.vue'// 错误
const userStore = useUserStore()const pinia = createPinia()
const app = createApp(App)
app.use(pinia)// 正确,因为 pinia 实例现在被激活
const userStore = useUserStore()

这篇关于《Vue3 基础知识》Pinia 01 之 基础的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1062562

相关文章

HTML5中的Microdata与历史记录管理详解

《HTML5中的Microdata与历史记录管理详解》Microdata作为HTML5新增的一个特性,它允许开发者在HTML文档中添加更多的语义信息,以便于搜索引擎和浏览器更好地理解页面内容,本文将探... 目录html5中的Mijscrodata与历史记录管理背景简介html5中的Microdata使用M

html5的响应式布局的方法示例详解

《html5的响应式布局的方法示例详解》:本文主要介绍了HTML5中使用媒体查询和Flexbox进行响应式布局的方法,简要介绍了CSSGrid布局的基础知识和如何实现自动换行的网格布局,详细内容请阅读本文,希望能对你有所帮助... 一 使用媒体查询响应式布局        使用的参数@media这是常用的

HTML5表格语法格式详解

《HTML5表格语法格式详解》在HTML语法中,表格主要通过table、tr和td3个标签构成,本文通过实例代码讲解HTML5表格语法格式,感兴趣的朋友一起看看吧... 目录一、表格1.表格语法格式2.表格属性 3.例子二、不规则表格1.跨行2.跨列3.例子一、表格在html语法中,表格主要通过< tab

Android Mainline基础简介

《AndroidMainline基础简介》AndroidMainline是通过模块化更新Android核心组件的框架,可能提高安全性,本文给大家介绍AndroidMainline基础简介,感兴趣的朋... 目录关键要点什么是 android Mainline?Android Mainline 的工作原理关键

Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案

《Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案》:本文主要介绍Vue3组件中getCurrentInstance()获取App实例,但是返回nu... 目录vue3组件中getCurrentInstajavascriptnce()获取App实例,但是返回n

JS+HTML实现在线图片水印添加工具

《JS+HTML实现在线图片水印添加工具》在社交媒体和内容创作日益频繁的今天,如何保护原创内容、展示品牌身份成了一个不得不面对的问题,本文将实现一个完全基于HTML+CSS构建的现代化图片水印在线工具... 目录概述功能亮点使用方法技术解析延伸思考运行效果项目源码下载总结概述在社交媒体和内容创作日益频繁的

前端CSS Grid 布局示例详解

《前端CSSGrid布局示例详解》CSSGrid是一种二维布局系统,可以同时控制行和列,相比Flex(一维布局),更适合用在整体页面布局或复杂模块结构中,:本文主要介绍前端CSSGri... 目录css Grid 布局详解(通俗易懂版)一、概述二、基础概念三、创建 Grid 容器四、定义网格行和列五、设置行

前端下载文件时如何后端返回的文件流一些常见方法

《前端下载文件时如何后端返回的文件流一些常见方法》:本文主要介绍前端下载文件时如何后端返回的文件流一些常见方法,包括使用Blob和URL.createObjectURL创建下载链接,以及处理带有C... 目录1. 使用 Blob 和 URL.createObjectURL 创建下载链接例子:使用 Blob

Vuex Actions多参数传递的解决方案

《VuexActions多参数传递的解决方案》在Vuex中,actions的设计默认只支持单个参数传递,这有时会限制我们的使用场景,下面我将详细介绍几种处理多参数传递的解决方案,从基础到高级,... 目录一、对象封装法(推荐)二、参数解构法三、柯里化函数法四、Payload 工厂函数五、TypeScript

mysql的基础语句和外键查询及其语句详解(推荐)

《mysql的基础语句和外键查询及其语句详解(推荐)》:本文主要介绍mysql的基础语句和外键查询及其语句详解(推荐),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录一、mysql 基础语句1. 数据库操作 创建数据库2. 表操作 创建表3. CRUD 操作二、外键