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

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

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

1. 安装

//Vuex
npm i vuex -S //Pinia
npm i pinia -S

2. 挂载

2.1 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 '@/store'
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已经挂载成功了

2.2 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中没有了mutationsmodulespinia不必以嵌套(通过modules引入)的方式引入模块,因为它的每个store便是一个模块,如storeAstoreB... 。在我们使用Vuex的时候每次修改state的值都需要调用mutations里的修改函数(下面会说到),因为Vuex需要追踪数据的变化,这使我们写起来比较繁琐。而pinia则不再需要mutations,同步异步都可在actions进行操作。

3. 修改状态

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

3.1 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内部进行便于检测。直接看图,一目了然

3.2 Pinia

  • 直接修改

相比于VuexPinia是可以直接修改状态的,并且调试工具能够记录到每一次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就行Vuexmutations修改state一样。其实这也是我比较推荐的一种修改状态的方式,就像上面说的,这样可以实现整个数据流程都在状态管理器内部,便于管理。

piniaStore/storeA.jsactions添加一个修改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()

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

5. getters

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

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

我被调用了!

3

3

3

我被调用了!

4

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

5.2 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
}
}
});

6. modules

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

6.1 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", {...});

6.2 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: truemoduleA

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

7. 结论

通过以上案例我们会发现PiniaVuex简洁许多,所以如果我们的项目是新项目的话建议使用Pinia

对比`Pinia `和` Vuex`,全面了解` Vue`状态管理的更多相关文章

  1. 结合 Vuex 和 Pinia 做一个适合自己的状态管理 nf-state

    一开始学习了一下 Vuex,感觉比较冗余,就自己做了一个轻量级的状态管理. 后来又学习了 Pinia,于是参考 Pinia 改进了一下自己的状态管理. 结合 Vuex 和 Pinia, 保留需要的功能 ...

  2. Vue状态管理vuex

    前面的话 由于多个状态分散的跨越在许多组件和交互间各个角落,大型应用复杂度也经常逐渐增长.为了解决这个问题,Vue提供了vuex.本文将详细介绍Vue状态管理vuex 引入 当访问数据对象时,一个 V ...

  3. vuex(vue状态管理)

    vuex(vue状态管理) 1.先安装vuex npm install vuex --save   2.在项目的src目录下创建store目录,并且新建index.js文件,然后创建vuex实例,引入 ...

  4. vue状态管理器(用户登录简单应用)

    技术点:通过vue状态管理器,对已经登录的用户显示不同的页面: 一  vue之状态管理器应用 主要用来存储cookie信息 与vue-cookies一起使用 安装:npm install vue-co ...

  5. 一文解析Pinia和Vuex,带你全面理解这两个Vue状态管理模式

    Pinia和Vuex一样都是是vue的全局状态管理器.其实Pinia就是Vuex5,只不过为了尊重原作者的贡献就沿用了这个看起来很甜的名字Pinia. 本文将通过Vue3的形式对两者的不同实现方式进行 ...

  6. Vue状态管理之Vuex

    Vuex是专为Vue.js设计的状态管理模式.采用集中存储组件状态它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 1.首先让我们从一个vue的计数应用开始 ...

  7. vue - 状态管理器 Vuex

    状态管理 vuex是一个专门为vue.js设计的集中式状态管理架构.状态?我把它理解为在data中的属性需要共享给其他vue组件使用的部分,就叫做状态.简单的说就是data中需要共用的属性.

  8. 五、vue状态管理模式vuex

    一.vuex介绍 Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 即data中属性同时有一 ...

  9. vuex vue状态管理

    第一步安装vuex(安装在生产环境) npm install vuex 第二步 src下新建store文件夹 用来专门放状态管理,store文件夹下新建四个js文件 index.js  actions ...

  10. VueX(vue状态管理)简单小实例

    VueX:状态管理 Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 核心模块:State. ...

随机推荐

  1. FMEA学习之PFMEA

    一.基础介绍 FMEA 是 Faliure Mode Effect Analysis 简称,翻译过来叫做失效模式分析,按我的理解,用白话说出来就是:对导致不符合生产质量不符合客户要求的问题会产生多么严 ...

  2. 数据分析---numpy模块

    前戏 NumPy(Numerical Python) 是 Python 语言中做科学计算的基础库.重在于数值计算,也是大部分Python科学计算库的基础,多用于在大型.多维数组上执行的数值运算. 快捷 ...

  3. 莫烦tensorflow学习记录 (6)卷积神经网络 CNN (Convolutional Neural Network)

    卷积 和 神经网络 莫烦大佬的原文章https://mofanpy.com/tutorials/machine-learning/tensorflow/intro-CNN/ 我的理解就是千层饼,鸡蛋烧 ...

  4. uniapp 页面跳转传值和接收

    前端面试题库地址:https://www.yuque.com/sxd_panda/sdluga 1.首先介绍最原始的跳转方法,类似于html中的a标签,不过在uniapp中需要将a标签换成 <n ...

  5. C#.Net筑基-String字符串超全总结 [深度好文]

    字符串是日常编码中最常用的引用类型了,可能没有之一,加上字符串的不可变性.驻留性,很容易产生性能问题,因此必须全面了解一下. 01.字符与字符编码 1.1.字符Char 字符 char 表示为 Uni ...

  6. LeetCode 449. Serialize and Deserialize BST 序列化和反序列化二叉搜索树 (Java)

    题目: Serialization is the process of converting a data structure or object into a sequence of bits so ...

  7. 解决java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone

    错误描述: 使用JDBC连接数据库是产生错误 应该是数据库时区问题,在url配置时设置serverTimezone = GMT即可 url = "jdbc:mysql://localhost ...

  8. 剑指Offer-54.字符流中第一个不重复的字符(C++/Java)

    题目: 请实现一个函数用来找出字符流中第一个只出现一次的字符.例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g".当从该字符流中读出前 ...

  9. ASP.NET MVC 出现: Uncaught ReferenceError: $ is not defined

    ASP.NET MVC 出现: Uncaught ReferenceError: $ is not defined 错误 将 _Layout.cshtml 中的三行代码,移动到 <head> ...

  10. SpringBoot指标监控功能

    SpringBoot指标监控功能 随时查看SpringBoot运行状态,将状态以josn格式返回 添加Actuator功能 Spring Boot Actuator可以帮助程序员监控和管理Spring ...