Pinia学习笔记之--核心概念Actions
Actions
Actions
相当于组件中的方法。他们可以被定义在defineStore()
的actions
属性下,它们非常适合定义业务逻辑。
export const useStore = defineStore('main', {state: () => ({counter: 0,}),actions: {increment() {this.counter++},randomizeCounter() {this.counter = Math.round(100 * Math.random())},},
})
与getter
一样,actions
通过this
(和自动完成✨)支持来访问整个store
实例。与它们不同的是,actions
可以是异步的,您可以在其中await
任何API调用或甚至其他操作!下面是一个使用Mande
的例子。注意,你只需要得到一个Promise
,至于使用的库并不重要,你甚至可以使用原生的fetch
函数(仅适用于浏览器):
import { mande } from 'mande'const api = mande('/api/users')export const useUsers = defineStore('users', {state: () => ({userDate: null}),actions: {async registerUser(login, password) {try {this.userDate = await api.post({ login, password})showTooltip(`Welcome back ${this.userData.name}!`)} catch (error) {showTooltip(error)// 让组件显示错误信息return error}}}
})
你可以完全自主的定义参数或返回的值。
当调用actions
,一切将会被自动推断出来!
Actions
像方法一样被调用:
export default defineComponent({setup () {const main = useMainStore()// 调用action作为store的一个方法main.randomizeCounter()return {}}
})
访问其它stores
的actions
要使用另一个store
,你可以直接在action
中使用它:
import { useAuthStore } from './auth-store'export const useSettingStore = 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')}}}
})
在setup()
中使用
你可以直接调用任何action
作为store
的方法:
export default {setup() {const store = useStore()store.fetchUserPreferences()}
}
使用选项API
对于以下示例,您可以假设创建了以下存储:
// Example File Path:
// ./src/stores/counterStore.jsimport { defineStore } from 'pinia',const useCounterStore = defineStore('counterStore', {state: () => ({counter: 0}),actions: {increment() {this.counter++}}
})
使用setup()
虽然Composition API
并不适合所有人,但是setup()
钩子可以让Pinia
更容易在Options API
中使用。不需要额外的帮助函数!
import { useCounterStore } from '../stores/counterStore'export default {setup() {const counterStore = useCounterStore()return { counterStore }},methods: {incrementAndPrint() {this.counterStore.increment()console.log('New Count:', this.counterStore.count)},},
}
不使用setup()
如果你根本不想使用Composition API
,你可以使用mapActions()
助手来将actions
属性映射为组件中的方法:
import { mapActions } from 'pinia'
import { useCounterStore } from '../stores/counterStore'export default {methods: {// 在组件内可以通过this.increment()访问// 和使用 store.increment()相同...mapActions(useCounterStore, ['increment'])// 和上面一样,但是被注册成this.myOwnName()...mapActions(useCounterStore, { myOwnName: 'doubleCounter' }),},
}
订阅actions
可以使用store.$onAction()
来观察操作及其结果。传递给它的回调函数在动作本身之前执行。after
允许您在动作执行成功或resolves
之后执行一个函数。类似地,onError
允许你在动作抛出或拒绝时执行一个函数。这在运行时跟踪错误是非常有用的。
下面是一个在运行操作之前和resolve
/reject
操作之后记录日志的例子。
const unsubscribe = someStore.$onAction(({name, // name of the actionstore, // store instance, same as `someStore`args, // array of parameters passed to the actionafter, // hook after the action returns or resolvesonError, // hook if the action throws or rejects}) => {// a shared variable for this specific action callconst startTime = Date.now()// this will trigger before an action on `store` is executedconsole.log(`Start "${name}" with params [${args.join(', ')}].`)// this will trigger if the action succeeds and after it has fully run.// it waits for any returned promisedafter((result) => {console.log(`Finished "${name}" after ${Date.now() - startTime}ms.\nResult: ${result}.`)})// this will trigger if the action throws or returns a promise that rejectsonError((error) => {console.warn(`Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`)})}
)// manually remove the listener
unsubscribe()
默认情况下,操作订阅被绑定到添加它们的组件上(如果store
在组件的setup()
中)。这意味着,当组件被卸载后,他们将会被自动移除。如果你想在组件卸载后保持订阅,通过true
作为第二个参数去把订阅从当前组件中分离出来。
export default {setup() {const someStore = useSomeStore()// 这个订阅将会被保留,在组件被卸载之后someStore.$onAction(callback, true)}
}
Pinia学习笔记之--核心概念Actions相关推荐
- 利用计算机技术实现对文本篇章,自然语言处理NLP学习笔记一:概念与模型初探...
前言 先来看一些demo,来一些直观的了解. 自然语言处理: 可以做中文分词,词性分析,文本摘要等,为后面的知识图谱做准备. 知识图谱: 还有2个实际应用的例子,加深对NLP的理解 九歌机器人: 微软 ...
- Docker:学习笔记(1)——基础概念
Docker:学习笔记(1)--基础概念 Docker是什么 软件开发后,我们需要在测试电脑.客户电脑.服务器安装运行,用户计算机的环境各不相同,所以需要进行各自的环境配置,耗时耗力.为了解决这个问题 ...
- HTML/CSS学习笔记01【概念介绍、基本标签】
w3cschool菜鸟教程.CHM(腾讯微云):https://share.weiyun.com/c1FaX6ZD HTML/CSS学习笔记01[概念介绍.基本标签.表单标签][day01] HTML ...
- 浅说深度学习(1):核心概念
浅说深度学习(1):核心概念 原文来自Nvidia开发者社区:Deep Learning in a Nutshell: Core Concepts 作者:Tim Dettmers, Author at ...
- node.js学习笔记5——核心模块1
node.js学习笔记5--核心模块1 Node.js核心模块主要内容包括:(1)全局对象 (2)常用工具 (3)事件机制 (4)文件系统访问 (5)HTTP服务器与客户端 一: 全局对象 Node. ...
- 网络流算法学习笔记——最大流问题基本概念和Ford-Fulkerson方法(标号法C++实现)
屈婉玲<算法设计与分析>第2版第7章网络流算法学习笔记. 基本概念 最大流问题,相当于有从s到t的供水系统,每段路径都有限定流量,除了s.t两地外,每个中间点都不能滞留,从s流入多少,就从 ...
- TCP/IP详解学习笔记(1)-基本概念
为什么会有TCP/IP协议 在世界上各地,各种各样的电脑运行着各自不同的操作系统为大家服务,这些电脑在表达同一种信息的时候所使用的方法是千差万别.就好像圣经中上帝打乱了各地人的口音,让他们无法合作一样 ...
- 冰冰学习笔记:进程概念
欢迎各位大佬光临本文章!!! 还请各位大佬提出宝贵的意见,如发现文章错误请联系冰冰,冰冰一定会虚心接受,及时改正. 本系列文章为冰冰学习编程的学习笔记,如果对您也有帮助,还请各位大佬.帅哥.美女点点支 ...
- Elasticsearch学习系列-ElasticSearch 核心概念
导语 这篇文章中主要分享关于ElasticSearch相关的基础知识,介绍一下关于ElasticSearch相关的术语以及它的架构相关的内容 文章目录 ElasticSearch 简介 Elast ...
最新文章
- MySQL中更改表操作
- java测试不成功_为什么我的Java布尔测试总是失败?
- macOS 10.12 Sierra 中文官网正式推出
- Android源码分析--MediaServer源码分析(二)
- c 语言名称的作用域,C 作用域规则
- 详细解释到底啥是共轭先验(用本科知识来解释)
- yaahp层次分析法步骤_综合评价方法之层次分析法,选择再也难不倒你!
- 计算机休眠怎么唤醒,电脑休眠后,就无法唤醒了?怎么办?快速教你解决这个问题...
- php 导出excel 特殊字符,PHPEXCEL导出,存在特殊字符遇到的问题
- GitLab 8.9 新增文件锁 和 U2F硬件支持
- 远程控制多台服务器,perl远程执行多台服务器shell命令
- 华为metebook电脑如何修改应用商店中新应用的默认安装路径
- JQuery AJAX 的表单提交
- 谷歌浏览器配置微信浏览器_微信网页版 - Chrome社交与通讯插件 - 画夹插件网
- 如何按州跟踪缺席选票
- 编译器优化级别O3引入的bug
- response.getStatusCode()==200什么意思
- 从钉钉后台API获取企业通信录
- 关于 Android O 的 treble/hidl
- DSP28035控制舵机
热门文章
- C++迷宫最短路径问题BFS
- Hyperledger Fabric 环境搭建报错
- c# 微信支付V3商家转账到零钱避坑宝典(一)
- X86平台操作系统概览 zz
- “创业吃过饼,国企养过老,android开发零基础
- linux 禁用usb驱动程序,如何使用musb_hdrc Linux驱动程序断开特定的USB设备?
- 关于MFi认证你所必须要知道的事情
- 怎么注册微软云服务器,如何创建和部署云服务(经典) | Microsoft Docs
- unity获取android内存大小,使用SystemInfo类获取Unity3D运行设备的各类信息(CPU类型,显卡类型等)...
- 无人驾驶时代的室外组网技术研究