Pinia 和 Vuex ,理解这两个 Vue 状态管理模式

news2024/9/25 11:19:04

Pinia和Vuex一样都是是vue的全局状态管理器。其实Pinia就是Vuex5,只不过为了尊重原作者的贡献就沿用了这个看起来很甜的名字Pinia。

本文通过Vue3的形式对两者的不同实现方式进行对比,让你在以后工作中无论使用到Pinia还是Vuex的时候都能够游刃有余。

既然我们要对比两者的实现方式,那么我们肯定要先在我们的Vue3项目中引入这两个状态管理器(实际项目中千万不要即用Vuex又用Pinia,不然你会被同事请去喝茶的。下面就让我们看下它们的使用方式。

安装

  • Vuex

npm i vuex -S
  • Pinia

npm i pinia -S

挂载

Vuex

在src目录下新建vuexStore,实际项目中你只需要建一个store目录即可,由于我们需要两种状态管理器,所以需要将其分开并创建两个store目录

新建vuexStore/index.js

import { createStore } from 'vuex'

export default createStore({
    //全局state,类似于vue种的data
    state() {
      return {
        vuexmsg: "hello vuex",
        name: "xiaoyue",
      };
    },


    //修改state函数
    mutations: {
    },

    //提交的mutation可以包含任意异步操作
    actions: {
    },

    //类似于vue中的计算属性
    getters: {
    },

    //将store分割成模块(module),应用较大时使用
    modules: {
    }
})

main.js引入

import { createApp } from 'vue'
import App from './App.vue'
import store from '@/vuexStore'
createApp(App).use(store).mount('#app')

App.vue测试

<template>
  <div></div>
</template>
<script setup>
import { useStore } from 'vuex'
let vuexStore = useStore()
console.log(vuexStore.state.vuexmsg); //hello vuex
</script>

页面正常打印hello vuex说明我们的Vuex已经挂载成功了

Pinia

  • 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

src下新建piniaStore/storeA.js

import { defineStore } from "pinia";

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

  • App.vue使用

<template>
  <div></div>
</template>
<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
console.log(piniaStoreA.piniaMsg); //hello pinia
</script>

从这里我们可以看出pinia中没有了mutations和modules,pinia不必以嵌套(通过modules引入)的方式引入模块,因为它的每个store便是一个模块,如storeA,storeB... 。

在我们使用Vuex的时候每次修改state的值都需要调用mutations里的修改函数(下面会说到),因为Vuex需要追踪数据的变化,这使我们写起来比较繁琐。而pinia则不再需要mutations,同步异步都可在actions进行操作,至于它没有了mutations具体是如何最终到state变化的,这里我们不过多深究,大概好像应该是通过hooks回调的形式解决的把(我也没研究过,瞎猜的。

修改状态

获取state的值从上面我们已经可以一目了然的看到了,下面让我们看看他俩修改state的方法吧

vuex

vuex在组件中直接修改state,如App.vue

<template>
  <div>{{vuexStore.state.vuexmsg}}</div>
</template>
<script setup>
import { useStore } from 'vuex'
let vuexStore = useStore()
vuexStore.state.vuexmsg = 'hello juejin'
console.log(vuexStore.state.vuexmsg)

</script>

可以看出我们是可以直接在组件中修改state的而且还是响应式的,但是如果这样做了,vuex不能够记录每一次state的变化记录,影响我们的调试。

当vuex开启严格模式的时候,直接修改state会抛出错误,所以官方建议我们开启严格模式,所有的state变更都在vuex内部进行,在mutations进行修改。例如vuexStore/index.js:

import { createStore } from "vuex";

export default createStore({
  strict: true,
  //全局state,类似于vue种的data
  state: {
    vuexmsg: "hello vuex",
  },

  //修改state函数
  mutations: {
    setVuexMsg(state, data) {
      state.vuexmsg = data;
    },
  },

  //提交的mutation可以包含任意异步操作
  actions: {},

  //类似于vue中的计算属性
  getters: {},

  //将store分割成模块(module),应用较大时使用
  modules: {},
});

当我们需要修改vuexmsg的时候需要提交setVuexMsg方法,如App.vue

<template>
  <div>{{ vuexStore.state.vuexmsg }}</div>
</template>
<script setup>
import { useStore } from 'vuex'
let vuexStore = useStore()
vuexStore.commit('setVuexMsg', 'hello juejin')
console.log(vuexStore.state.vuexmsg) //hello juejin

</script>

或者我们可以在actions中进行提交mutations修改state:

import { createStore } from "vuex";
export default createStore({
  strict: true,
  //全局state,类似于vue种的data
  state() {
    return {
      vuexmsg: "hello vuex",
    }
  },

  //修改state函数
  mutations: {
    setVuexMsg(state, data) {
      state.vuexmsg = data;
    },
  },

  //提交的mutation可以包含任意异步操作
  actions: {
    async getState({ commit }) {
      //const result = await xxxx 假设这里进行了请求并拿到了返回值
      commit("setVuexMsg", "hello juejin");
    },
  }
});

组件中使用dispatch进行分发actions

<template>
  <div>{{ vuexStore.state.vuexmsg }}</div>
</template>
<script setup>
import { useStore } from 'vuex'
let vuexStore = useStore()
vuexStore.dispatch('getState')

</script>

一般来说,vuex中的流程是首先actions一般放异步函数,拿请求后端接口为例,当后端接口返回值的时候,actions中会提交一个mutations中的函数,然后这个函数对vuex中的状态(state)进行一个修改,组件中再渲染这个状态,从而实现整个数据流程都在vuex内部进行便于检测。直接看图,一目了然

Pinia

  • 直接修改

相比于Vuex,Pinia是可以直接修改状态的,并且调试工具能够记录到每一次state的变化,如App.vue

<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>

  • $patch

使用$patch方法可以修改多个state中的值,比如我们在piniaStore/storeA.js中的state增加一个name

import { defineStore } from "pinia";

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

然后我们在App.vue中进行修改这两个state

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

当然也是支持修改单个状态的如

piniaStoreA.$patch({
  name: 'daming'
})

$patch还可以使用函数的方式进行修改状态

import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
cartStore.$patch((state) => {
  state.name = 'daming'
  state.piniaMsg = 'hello juejin'
})
  • 在actions中进行修改

不同于Vuex的是,Pinia去掉了mutations,所以在actions中修改state就行Vuex在mutations修改state一样。其实这也是我比较推荐的一种修改状态的方式,就像上面说的,这样可以实现整个数据流程都在状态管理器内部,便于管理。

在piniaStore/storeA.js的actions添加一个修改name的函数

import { defineStore } from "pinia";
export const storeA = defineStore("storeA", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
      name: "xiao yue",
    };
  },
  actions: {
    setName(data) {
      this.name = data;
    },
  },
});

组件App.vue中调用不需要再使用dispatch函数,直接调用store的方法即可

import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
piniaStoreA.setName('daming')
  • 重置state

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

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

Pinia解构(storeToRefs)

当我们组件中需要用到state中多个参数时,使用解构的方式取值往往是很方便的,但是传统的ES6解构会使state失去响应式,比如组件App.vue,我们先解构取得name值,然后再去改变name值,然后看页面是否变化

<template>
  <div>{{ name }}</div>
</template>
<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
let { piniaMsg, name } = piniaStoreA
piniaStoreA.$patch({
  name: 'daming'
})

</script>

浏览器展示如下

 

 

我们可以发现浏览器并没有更新页面为daming

为了解决这个问题,Pinia提供了一个结构方法storeToRefs,我们将组件App.vue使用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>

再看下页面变化

 

我们发现页面已经被更新成daming了

getters

其实Vuex中的getters和Pinia中的getters用法是一致的,用于自动监听对应state的变化,从而动态计算返回值(和vue中的计算属性差不多),并且getters的值也具有缓存特性

Pinia

我们先将piniaStore/storeA.js改为

import { defineStore } from "pinia";

export const storeA = defineStore("storeA", {
  state: () => {
    return {
      count1: 1,
      count2: 2,
    };
  },
  getters: {
    sum() {
      console.log('我被调用了!')
      return this.count1 + this.count2;
    },
  },
});

然后在组件App.vue中获取sum

<template>
  <div>{{ piniaStoreA.sum }}</div>
</template>
<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
console.log(piniaStoreA.sum) //3

</script>

让我们来看下什么是缓存特性。首先我们在组件多次访问sum再看下控制台打印

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)

 

从打印结果我们可以看出只有在首次使用用或者当我们改变sum所依赖的值的时候,getters中的sum才会被调用

Vuex

Vuex中的getters使用和Pinia的使用方式类似,就不再进行过多说明,写法如下vuexStore/index.js

import { createStore } from "vuex";

export default createStore({
  strict: true,
  //全局state,类似于vue种的data
  state: {
    count1: 1,
    count2: 2,
  },

  //类似于vue中的计算属性
  getters: {
    sum(state){
      return state.count1 + state.count2
    }
  }


});

modules

如果项目比较大,使用单一状态库,项目的状态库就会集中到一个大对象上,显得十分臃肿难以维护。所以Vuex就允许我们将其分割成模块(modules),每个模块都拥有自己state,mutations,actions...。而Pinia每个状态库本身就是一个模块。

Pinia

Pinia没有modules,如果想使用多个store,直接定义多个store传入不同的id即可,如:

import { defineStore } from "pinia";

export const storeA = defineStore("storeA", {...});
export const storeB = defineStore("storeB", {...});
export const storeC = defineStore("storeB", {...});

Vuex

一般来说每个module都会新建一个文件,然后再引入这个总的入口index.js中,这里为了方便就写在了一起

import { createStore } from "vuex";
const moduleA = {
  state: () => ({ 
    count:1
   }),
  mutations: {
    setCount(state, data) {
      state.count = data;
    },
  },
  actions: {
    getuser() {
      //do something
    },
  },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

export default createStore({
  strict: true,
  //全局state,类似于vue种的data
  state() {
    return {
      vuexmsg: "hello vuex",
      name: "xiaoyue",
    };
  },
  modules: {
    moduleA,
    moduleB
  },
});

使用moduleA

import { useStore } from 'vuex'
let vuexStore = useStore()
console.log(vuexStore.state.moduleA.count) //1
vuexStore.commit('setCount', 2)
console.log(vuexStore.state.moduleA.count) //2
vuexStore.dispatch('getuser')

一般我们为了防止提交一些mutation或者actions中的方法重名,modules一般会采用命名空间的方式 namespaced: true 如moduleA:

const moduleA = {
  namespaced: true,
  state: () => ({
    count: 1,
  }),
  mutations: {
    setCount(state, data) {
      state.count = data;
    },
  },
  actions: {
    getuser() {
      //do something
    },
  },
}

此时如果我们再调用setCount或者getuser

vuexStore.commit('moduleA/setCount', 2)
vuexStore.dispatch('moduleA/getuser')

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

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

相关文章

Linux下在日志中打印时间戳

1、背景介绍&#xff1a;在实验过程中需要记录任务运行情况&#xff0c;为此需要在日志中增加时间戳打印信息&#xff0c;方便事后查看。 2、实现方法 示例如下&#xff1a; #include <stdio.h> #include <time.h> #include<string.h>void print_debug_me…

如何在iPhone上用ChatGPT替换Siri

To use ChatGPT with Siri on an iPhone or iPad, get an OpenAI API key and download the ChatGPT Siri shortcut. Enter your API key in the shortcut setup and select the GPT model you want to use, then hit “Add Shortcut.” Trigger the shortcut manually first t…

FreeRTOS实时操作系统(二)系统文件代码学习

文章目录 前言系统配置任务创建任务创建删除实践 前言 接着学习正点原子的FreeRTOS教程&#xff0c;涉及到一些详细的系统内文件代码 系统配置 可以通过各种的宏定义来实现我们自己的RTOS配置&#xff08;在FreeRTOSconfig.h&#xff09; “INCLUDE”&#xff1a;配置API函数…

【Java】catch里面抛出了异常finally里面的事务会提交吗?

文章目录 背景目前的代码直接实战演示单元测试总结 背景 我们公司的系统中有一个业务场景&#xff0c;需要第三方的账户数据同步到我们系统。 同步账号的同时&#xff0c;会将所有同步数据和是否成功记录到一张同步日志表中&#xff0c;方便排查问题和记录。 好了&#xff0c;…

window11系统CUDA、cuDNN 安装以及环境变量配置

文章目录 一&#xff0c;说明二&#xff0c;cuda的下载以及安装1. 确定自己电脑设备哪个版本cudaa. 点击左下角b. 点击左下角c.接着点击 组件 2. cuda的下载3. cuda的安装1. 双击 点击 ok2. 同意即可3. 这个随意哪个都行4.选择安装位置 接着下一步 三&#xff0c;cuda环境变量设…

Oracle安装时先决条件检查失败和[INS-35180] 无法检查可用内存问题解决

Oracle安装时先决条件检查失败和[INS-35180] 无法检查可用内存问题解决 问题&#xff1a; [INS-13001] 此操作系统不支持 Oracle 数据库问题原因解决方案 问题2&#xff1a;[INS-35180] 无法检查可用内存问题原因解决方案 问题&#xff1a; [INS-13001] 此操作系统不支持 Oracl…

Python面向对象编程-构建游戏和GUI 手把手项目教学(1.1)

总项目目标&#xff1a;设计一个简单的纸牌游戏程序&#xff0c;称为"Higher or Lower"&#xff08;高还是低&#xff09;。游戏中&#xff0c;玩家需要猜测接下来的一张牌是比当前牌高还是低。根据猜测的准确性&#xff0c;玩家可以得到或失去相应的积分。 项目1.1…

循环码的编码、译码与循环冗余校验

本专栏包含信息论与编码的核心知识&#xff0c;按知识点组织&#xff0c;可作为教学或学习的参考。markdown版本已归档至【Github仓库&#xff1a;https://github.com/timerring/information-theory 】或者公众号【AIShareLab】回复 信息论 获取。 文章目录 循环码的编码循环码…

实现 strStr

在一个串中查找是否出现过另一个串&#xff0c;这是KMP的看家本领。 28. 实现 strStr() 力扣题目链接 实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串&#xff0c;在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在&…

七、docker-compose方式运行Jenkins,更新Jenkins版本,添加npm node环境

docker-compose方式运行Jenkins&#xff0c;更新Jenkins版本&#xff0c;添加npm node环境 一、docker-compose方式安装运行Jenkins 中发现Jenkins版本有点老&#xff0c;没有node环境&#xff0c;本节来说下更新jenkins 及添加构建前端的node环境。 1. 准备好docker-compose…

算法刷题-双指针-二分法

27. 移除元素 力扣题目链接 给你一个数组 nums 和一个值 val&#xff0c;你需要 原地 移除所有数值等于 val 的元素&#xff0c;并返回移除后数组的新长度。 不要使用额外的数组空间&#xff0c;你必须仅使用 O(1) 额外空间并原地修改输入数组。 元素的顺序可以改变。你不需…

XSS数据接收平台——蓝莲花(BlueLotus)

文章目录 一、前言二、安装三、使用1、我的JS创建一个模板2、使用创建的模板攻击3、打开攻击的目标&#xff08;这里选择pikachu靶场的存储型XSS模块测试&#xff09;4、查看返回的数据 一、前言 蓝莲花平台是清华大学曾经的蓝莲花战队搭建的平台&#xff0c;该平台用于接收xs…

【QQ界面展示-通知的发布和监听 Objective-C语言】

一、来,看看,我们先给大家介绍一下通知 1.那么,这个通知,我们就是要给大家介绍三个东西 1)一个是通知的发布:如何发布通知 2)一个是通知的监听:发布以后,如何监听通知 3)一个是通知的移除:注意,通知一定要怎么样,最后,移除, 2.当你监听了一个通知以后,当你…

【Proteus仿真】51单片机+8255A IO扩展例程

【Proteus仿真】51单片机+8255A IO扩展例程 📍相关参考:51单片机8255A扩展IO口🎬Proteus仿真演示: 📓8255A与51单片机连接 🌿51单片机的P0口作为数据总线使用,与8255A的D7~D0数据信号线进行连接,当P00 - P07不作为8255A 的A、B、C端口地址使用时,可以不接上拉电阻…

3.部署glance服务(镜像获取组件)

身份认证服务部署完毕之后&#xff0c;部署 glance 映像服务&#xff0c;映像服务可以帮助用户发现、注册、检索虚拟机镜像&#xff0c;就是说 启动实例的镜像是放在这里的 。 默认镜像存储目录为&#xff1a; /var/lib/glance/images/ controller节点 在安装和配置 glance …

lua的元表与元方法理解

元表 在 Lua 中&#xff0c;元表&#xff08;metatable&#xff09;是一种特殊的表&#xff0c;用于定义另一个表的行为。每个表都有一个关联的元表&#xff0c;通过元表可以重载表的各种操作&#xff0c;例如索引、新索引、相加等。在 Lua 中&#xff0c;元表的使用非常灵活&…

【Soft-prompt Tuning for Large Language Models to Evaluate Bias 论文略读】

Soft-prompt Tuning for Large Language Models to Evaluate Bias 论文略读 INFORMATIONAbstract1 Introduction2 Related work3 Methodology3.1 Experimental setup 4 Results5 Discussion & Conclusion总结A Fairness metricsB Hyperparmeter DetailsC DatasetsD Prompt …

Intellij IDEA设置“选中变量或方法”的背景颜色、字体颜色(Mark Occurrences)

背景 IDEA 中选中一个变量就会将所有的变量相关变量标出来&#xff0c;这样就很方便知道这个变量出现的地方。Eclipse里头把这个功能叫做 Mark Occurrences&#xff0c;IDEA 里不知道怎么称呼。 我们要解决的痛点就是提示不明显&#xff0c;如下图所示&#xff0c;Macbook这么…

RocketMQ一条消息从生产者到消费者的流程

目录 1. rocketmq 中的角色介绍 2. 一条消息从生产者到消费者的所有流程&#xff08;简版&#xff09; 3. 一条消息从生产者到消费者的所有流程 1. rocketmq 中的角色介绍 生产者 producer 生产、创造消息&#xff0c;会把消息发送到 broker 中消息代理服务 broker 负责消息…

小白怎么入门网络安全?看这篇就够啦!

由于我之前写了不少网络安全技术相关的故事文章&#xff0c;不少读者朋友知道我是从事网络安全相关的工作&#xff0c;于是经常有人在微信里问我&#xff1a; 我刚入门网络安全&#xff0c;该怎么学&#xff1f;要学哪些东西&#xff1f;有哪些方向&#xff1f;怎么选&#xff…