跳到主要内容位置

Pinia 和 Vuex 谁更吊

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

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 变化的

修改状态#

获取 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); //xiaoyuepiniaStoreA.$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 } = piniaStoreApiniaStoreA.$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); //1vuexStore.commit("setCount", 2);console.log(vuexStore.state.moduleA.count); //2vuexStore.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");