Pinia 上手使用(store、state、getters、actions)

news2024/9/22 11:42:52

参考链接:https://juejin.cn/post/7121209657678364685
Pinia官方:https://pinia.vuejs.org/zh/introduction.html

一、安装

npm i pinia -S

二、main.js 引入

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

三、创建 store

  • 可通过 defineStore 创建 多个 store (这与 vuex 只可以创建一个 store不同),所以 不再需要 modules(每个 store 便是一个模块)
  • 不再使用 mutations 作为 直接修改state 的方式
  • 支持以往的 options 创建形式,也可以使用 组合式函数定义一个store(像 setup 一样)

1、通过 options 创建

例如在 src下新建 piniaStore/storeA.js

import { defineStore } from "pinia";

export const storeA = defineStore("storeA", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
    };
  },
  getters: {},
  actions: {},
})

2、通过组合式函数创建

  • ref() 就是 state 属性
  • computed() 就是 getters
  • function() 就是 actions
export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

四、获取状态

1、在 <script setup> 中

<template>
  <div></div>
</template>

<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()

console.log(piniaStoreA.piniaMsg); //hello pinia
</script>

2、在 setup( ) 中

<script>
import { useCounterStore } from '../stores/counter'

export default defineComponent({
  setup() {
    const counterStore = useCounterStore()

    return { counterStore }
  },
  computed: {
    quadrupleCounter() {
      return this.counterStore.count * 2
    },
  },
  methods: {
    incrementAndPrint() {
      // 使用方法、状态,通过整个 store(因为没有解构)
      this.counterStore.increment()
      console.log('New Count:', this.counterStore.count)
    },
  },
})
</script>

五、修改状态

1、直接赋值修改

<template>
  <div>{{ piniaStoreA.piniaMsg }}</div>
</template>

<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()

console.log(piniaStoreA.piniaMsg); //hello pinia

piniaStoreA.piniaMsg = 'hello juejin'
console.log(piniaStoreA.piniaMsg); //hello juejin
</script>

2、使用 $patch 修改单个或多个状态

  • 可传入对象 修改
import { defineStore } from "pinia";

export const storeA = defineStore("storeA", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
      name: "xiaoyue",
    };
  },
  getters: {},
  actions: {},
});
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
console.log(piniaStoreA.name); //xiaoyue

piniaStoreA.$patch({
  piniaMsg: 'hello juejin',
  name: 'daming'
})

console.log(piniaStoreA.name);//daming
  • 也可传入 函数 修改
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()

piniaStoreA.$patch((state) => {
  state.name = 'daming'
  state.piniaMsg = 'hello juejin'
})

3、在 actions 中进行修改

  • Pinia 去掉了 mutations,所以在 actions 中修改 state 就行
  • 使用 actions 时,像调用 methods 一样直接调用即可
import { defineStore } from "pinia";
export const storeA = defineStore("storeA", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
      name: "xiao yue",
    };
  },
  actions: {
    setName(data) {
      this.name = data;
    },
  },
});
// script中使用
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()

piniaStoreA.setName('daming')
<!-- 模板中使用 -->
<button @click="piniaStoreA.setName()">点击</button>

4、使用 $reset 重置 state

Pinia 可以使用 $reset 将状态 重置为初始值

import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()

piniaStoreA.$reset()

六、解构

在上述使用中,我们都是通过 整个 store 来使用内部的 state 等,怎么解构使用呢?

1、错误示范

传统的 ES6解构 会使 state 失去响应式

<template>
  <div>{{ name }}</div>
</template>

<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()

let { piniaMsg, name } = piniaStoreA

piniaStoreA.$patch({
  name: 'daming'    // 更新失败
})
</script>

2、正确方式

Pinia 提供了一个解构方法 storeToRefs

<template>
  <div>{{ name }}</div>
</template>

<script setup>
import { storeA } from '@/piniaStore/storeA'
import { storeToRefs } from 'pinia'
let piniaStoreA = storeA()

let { piniaMsg, name } = storeToRefs(piniaStoreA)

piniaStoreA.$patch({
  name: 'daming'
})
</script>

七、getters

1、使用 getters

  • Pinia 中的 getters 和 Vuex 的 getters 用法是一致的, 也具有 缓存 特性
  • getter1 访问 getter2 时,通过 this
import { defineStore } from "pinia";

export const storeA = defineStore("storeA", {
  state: () => {
    return {
      count1: 1,
      count2: 2,
    };
  },
  getters: {
    sum (state) {
      console.log('我被调用了!')
      return state.count1 + state.count2;
    },
    sum2 () {
       // 访问其他 getter 时,通过this
       return this.sum + 1
    }
  },
});
<template>
  <div>{{ piniaStoreA.sum }}</div>
</template>

<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()

console.log(piniaStoreA.sum) //3
</script>

2、 缓存验证

import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
console.log(piniaStoreA.sum)
console.log(piniaStoreA.sum)
console.log(piniaStoreA.sum)
piniaStoreA.count1 = 2
console.log(piniaStoreA.sum)

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/535859.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

[FMC152]AD9208的2 路2GSPS/2.6GSPS/3GSPS 14bit AD 采集FMC 子卡模块中文版本设计资料及调试经验

板卡概述 FMC152 是一款基于VITA57.1 标准的&#xff0c;实现2 路14-bit、2GSPS/2.6GSPS/3GSPS AD 采集FMC 子卡模块。该模块可直接与FPGA 载卡配合使用&#xff0c;板卡ADC 器件采用ADI 公司的AD9208 芯片&#xff0c;&#xff0c;与ADI 公司的AD9689 可以实现PIN 脚兼容。该…

Android平台如何实现外部RTSP|RTMP流注入轻量级RTSP服务模块(内网RTSP网关)

技术背景 今天分享的是外部RTSP或RTMP流&#xff0c;拉取后注入到本地轻量级RTSP服务模块&#xff0c;供内网小并发场景下使用&#xff0c;这里我们叫做内网RTSP网关模块。 内网RTSP网关模块&#xff0c;系内置轻量级RTSP服务模块扩展&#xff0c;完成外部RTSP/RTMP数据拉取并…

挖呀挖和ChatGPT-UMLChina建模知识竞赛第4赛季第1轮

DDD领域驱动设计批评文集>> 《软件方法》强化自测题集>> 《软件方法》各章合集>> 参考潘加宇在《软件方法》和UMLChina公众号文章中发表的内容作答。在本文下留言回答&#xff0c;先全部答对者得分&#xff0c;本轮总分为3分。 1. [单选] 以黄老师版“挖…

opengauss 的回归测试

目录 一、回归测试说明 二、单独执行测试用例&#xff08;开发调试&#xff09; 一、回归测试说明 opengauss/postgresql 的回归测试&#xff0c;通过执行SQL比较输出打印&#xff0c;判断代码修改是否改变了其它功能逻辑。 OG的回归测试大体上和PG类似&#xff0c;主要是通…

wordpress服务器搬家和更换域名的几个步骤

问题解说 其实wordpress换域名需要到数据库进行操作的,首先,你换域名也是有几种情况的; 换空间换域名 如果是上述问题,那么将FTP整站打包外,还需要将数据库里的所有数据表也打包,数据库是进phpmyadmin里打包的,两个都打包后,然后分别上传到新的空间ftp和数据库里,然…

什么是投入产出比(ROI)以及如何提升投入产出比?

投入产出比&#xff08;ROI&#xff09;是一种衡量企业或项目投资效益的指标&#xff0c;它可以帮助企业评估投资回报情况&#xff0c;并制定更加明智的投资决策。本文将为大家介绍什么是投入产出比&#xff08;ROI&#xff09;以及如何提升投入产出比。 一、什么是投入产出比&…

【计算机网络 - 第四章】网络层:数据平面

目录 一、网络层概述 1、主要作用 2、控制平面方法 3、网络层提供的两种服务 二、路由器工作原理 1、路由器总体结构 2、输入、输出端口处理 &#xff08;1&#xff09;输入端口 &#xff08;2&#xff09;输出端口 3、交换 &#xff08;1&#xff09;经内存交换 &…

后端实习产出--通过自定义注解、反射、进行切面编程实现一个转化工具

前置知识&#xff1a; 需要会自定义注解方法自定义注解字段AOP切面编程&#xff0c;反射等... 核心代码结构&#xff1a; 核心代码实现&#xff1a; package com.***.config;import cn.hutool.core.util.StrUtil; import com.google.common.collect.Maps; import com.***.co…

【pyq文案】可可爱爱の朋友圈文案

1.我在该生儿育女的年纪&#xff0c;选择了生椰拿铁 2.我妈年轻时候工资2000&#xff0c;我现在工资也2000&#xff0c;这就叫薪火相传 3.不要讨厌自己&#xff0c;有什么事怪星座生肖八字和mbti就好了 4.人是会和动物共情的&#xff0c;我开始理解急每天早起&#xff0c;然…

FL Studio2023最新中文免费版水果音乐制作软件

FL Studio(水果音乐制作软件)是一款强大的音乐制作编曲软件&#xff0c;非常容易上手。FL让你的计算机就像是全功能的录音室&#xff0c;漂亮的大混音盘&#xff0c;先进的创作工具&#xff0c;让你的音乐突破想象力的限制。一款强大的音乐制作软件&#xff0c;可以进行音乐编曲…

云计算期中测试

云计算期中测试 文章目录 云计算期中测试一、前言二、第一题1、命令方式2、java API方式 三、第二题1、创建CSV文件并将其上传到HDFS2、编写利用MapReduce框架的java代码3、打包java项目4、在Hadoop集群上提交jar文件来运行MapReduce作业 一、前言 在实验开始之前我们需要在虚…

MySQL高级_第05章_存储引擎

MySQL高级_第05章_存储引擎 1. 查看存储引擎 查看mysql提供什么存储引擎&#xff1a; show engines ; show engines \G ; 显式如下&#xff1a; *************************** 1. row *************************** Engine : InnoDB Support: DEFAULT Comment : Su…

企业管理OA系统在企业数字化转型中带来的变化,简直难以想象

目前企业管理面临到哪些痛点 1.信息孤岛&#xff1a;企业内部信息流动不畅&#xff0c;各部门数据独立&#xff0c;互相之间信息难以共享和沟通。 2.流程繁琐&#xff1a;企业业务流程较为繁琐&#xff0c;审批流程漫长&#xff0c;给业务员和经理带来不必要的工作压力。 3.…

Hbase入门篇03---Java API使用,HBase高可用配置和架构设计

Hbase入门篇03---Java API使用&#xff0c;HBase高可用配置和架构设计 需求环境搭建表的CRUD坑命令执行卡住不动 &#xff1f;RegionServer只在本地127.0.0.1监听16020端口导致外网连接被拒RegionServer所在主机的/etc/hosts文件存在额外的回环地址映射信息,导致客户端拿到无法…

亚马逊云科技使用Inf2实例运行GPT-J-6B模型

在2019年的亚马逊云科技re:Invent上&#xff0c;亚马逊云科技发布了Inferentia芯片和Inf1实例这两个基础设施。Inferentia是一种高性能机器学习推理芯片&#xff0c;由亚马逊云科技定制设计&#xff0c;其目的是提供具有成本效益的大规模低延迟预测。时隔四年&#xff0c;2023年…

生成bean的注解@Component极其衍生和@ComponentScan@Configuration

Component Spring 2.5 以后&#xff0c;除了提供基本的 Component 注解之外&#xff0c;还提供了 Service Controller Repository 三个注解。在 Spring 源码中&#xff0c;后面三个注解都在开始部分引入了 Component 注解&#xff0c;除此以外这四个注解的源码内容没有任何区别…

Json介绍

文章目录 1. 什么是 JSON&#xff1f;2. JSON语法格式3. JSON在Java中的用途3.1 FastJSON1. FastJSON概述与下载2. FastJSON常用方法 3.2. Jackson1. Jackson下载与使用2. Jackson常用类与方法3. ObjectMapper类常用方法 1. 什么是 JSON&#xff1f; JSON:JavaScript Object N…

C语言函数大全-- _w 开头的函数(2)

C语言函数大全 本篇介绍C语言函数大全-- _w 开头的函数 1. _wexecl 1.1 函数说明 函数声明函数功能int _wexecl(const wchar_t *path, const wchar_t *arg0, ... /* , const wchar_t *arg1, ..., NULL */);它是一个 Windows 平台下的 C 标准库函数&#xff0c;用于在新进程…

〖大学生·技术人必学的职业规划白宝书 - 职业规划篇②〗- 进入职场前必须要考虑的问题

历时18个月&#xff0c;采访 850 得到的需求。 不管你是在校大学生、研究生、还是在职的小伙伴&#xff0c;该专栏有你想要的职业规划、简历、面试的答案。说明&#xff1a;该文属于 大学生技术人职业规划白宝书 专栏&#xff0c;购买任意白宝书体系化专栏可加入TFS-CLUB 私域社…

leecode106——使用中序遍历和后序遍历构造一棵二叉树

leecode106 中序遍历和后序遍历构造一棵二叉树 &#x1f50e;中序遍历和后续遍历的性质 在后序遍历中&#xff0c;最后一个元素二叉树的根节点 在中序遍历序列中&#xff0c;根节点的左边为左子树&#xff0c;右边为右子树 &#x1f50e;1.二叉树的还原过程描述 1.首先&am…