经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
一文详解Pinia和Vuex与两个Vue状态管理模式
来源:jb51  时间:2022/8/23 9:26:31  对本文有异议

前言

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

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

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

安装

Vuex

  1. npm i vuex -S

Pinia

  1. npm i pinia -S

挂载

Vuex

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

新建vuexStore/index.js

  1. import { createStore } from 'vuex'
  2.  
  3. export default createStore({
  4. //全局state,类似于vue种的data
  5. state() {
  6. return {
  7. vuexmsg: "hello vuex",
  8. name: "xiaoyue",
  9. };
  10. },
  11.  
  12.  
  13. //修改state函数
  14. mutations: {
  15. },
  16.  
  17. //提交的mutation可以包含任意异步操作
  18. actions: {
  19. },
  20.  
  21. //类似于vue中的计算属性
  22. getters: {
  23. },
  24.  
  25. //将store分割成模块(module),应用较大时使用
  26. modules: {
  27. }
  28. })

main.js引入

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

App.vue测试

  1. <template>
  2. <div></div>
  3. </template>
  4. <script setup>
  5. import { useStore } from 'vuex'
  6. let vuexStore = useStore()
  7. console.log(vuexStore.state.vuexmsg); //hello vuex
  8. </script>

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

Pinia

  • main.js引入
  1. import { createApp } from "vue";
  2. import App from "./App.vue";
  3. import {createPinia} from 'pinia'
  4. const pinia = createPinia()
  5. createApp(App).use(pinia).mount("#app");
  • 创建Store

src下新建piniaStore/storeA.js

  1. import { defineStore } from "pinia";
  2.  
  3. export const storeA = defineStore("storeA", {
  4. state: () => {
  5. return {
  6. piniaMsg: "hello pinia",
  7. };
  8. },
  9. getters: {},
  10. actions: {},
  11. });
  • App.vue使用
  1. <template>
  2. <div></div>
  3. </template>
  4. <script setup>
  5. import { storeA } from '@/piniaStore/storeA'
  6. let piniaStoreA = storeA()
  7. console.log(piniaStoreA.piniaMsg); //hello pinia
  8. </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

  1. <template>
  2. <div>{{vuexStore.state.vuexmsg}}</div>
  3. </template>
  4. <script setup>
  5. import { useStore } from 'vuex'
  6. let vuexStore = useStore()
  7. vuexStore.state.vuexmsg = 'hello juejin'
  8. console.log(vuexStore.state.vuexmsg)
  9.  
  10. </script>

可以看出我们是可以直接在组件中修改state的而且还是响应式的,但是如果这样做了,vuex不能够记录每一次state的变化记录,影响我们的调试。当vuex开启严格模式的时候,直接修改state会抛出错误,所以官方建议我们开启严格模式,所有的state变更都在vuex内部进行,在mutations进行修改。例如vuexStore/index.js:

  1. import { createStore } from "vuex";
  2.  
  3. export default createStore({
  4. strict: true,
  5. //全局state,类似于vue种的data
  6. state: {
  7. vuexmsg: "hello vuex",
  8. },
  9.  
  10. //修改state函数
  11. mutations: {
  12. setVuexMsg(state, data) {
  13. state.vuexmsg = data;
  14. },
  15. },
  16.  
  17. //提交的mutation可以包含任意异步操作
  18. actions: {},
  19.  
  20. //类似于vue中的计算属性
  21. getters: {},
  22.  
  23. //将store分割成模块(module),应用较大时使用
  24. modules: {},
  25. });

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

  1. <template>
  2. <div>{{ vuexStore.state.vuexmsg }}</div>
  3. </template>
  4. <script setup>
  5. import { useStore } from 'vuex'
  6. let vuexStore = useStore()
  7. vuexStore.commit('setVuexMsg', 'hello juejin')
  8. console.log(vuexStore.state.vuexmsg) //hello juejin
  9.  
  10. </script>

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

  1. import { createStore } from "vuex";
  2. export default createStore({
  3. strict: true,
  4. //全局state,类似于vue种的data
  5. state() {
  6. return {
  7. vuexmsg: "hello vuex",
  8. }
  9. },
  10.  
  11. //修改state函数
  12. mutations: {
  13. setVuexMsg(state, data) {
  14. state.vuexmsg = data;
  15. },
  16. },
  17.  
  18. //提交的mutation可以包含任意异步操作
  19. actions: {
  20. async getState({ commit }) {
  21. //const result = await xxxx 假设这里进行了请求并拿到了返回值
  22. commit("setVuexMsg", "hello juejin");
  23. },
  24. }
  25. });

组件中使用dispatch进行分发actions

  1. <template>
  2. <div>{{ vuexStore.state.vuexmsg }}</div>
  3. </template>
  4. <script setup>
  5. import { useStore } from 'vuex'
  6. let vuexStore = useStore()
  7. vuexStore.dispatch('getState')
  8.  
  9. </script>

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

Pinia

  • 直接修改

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

  1. <template>
  2. <div>{{ piniaStoreA.piniaMsg }}</div>
  3. </template>
  4. <script setup>
  5. import { storeA } from '@/piniaStore/storeA'
  6. let piniaStoreA = storeA()
  7. console.log(piniaStoreA.piniaMsg); //hello pinia
  8.  
  9. piniaStoreA.piniaMsg = 'hello juejin'
  10. console.log(piniaStoreA.piniaMsg); //hello juejin
  11.  
  12. </script>
  • $patch

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

  1. import { defineStore } from "pinia";
  2.  
  3. export const storeA = defineStore("storeA", {
  4. state: () => {
  5. return {
  6. piniaMsg: "hello pinia",
  7. name: "xiaoyue",
  8. };
  9. },
  10. getters: {},
  11. actions: {},
  12. });

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

  1. import { storeA } from '@/piniaStore/storeA'
  2. let piniaStoreA = storeA()
  3. console.log(piniaStoreA.name); //xiaoyue
  4. piniaStoreA.$patch({
  5. piniaMsg: 'hello juejin',
  6. name: 'daming'
  7. })
  8. console.log(piniaStoreA.name);//daming

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

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

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

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

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

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

  1. import { defineStore } from "pinia";
  2. export const storeA = defineStore("storeA", {
  3. state: () => {
  4. return {
  5. piniaMsg: "hello pinia",
  6. name: "xiao yue",
  7. };
  8. },
  9. actions: {
  10. setName(data) {
  11. this.name = data;
  12. },
  13. },
  14. });

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

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

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

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

Pinia解构(storeToRefs)

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

  1. <template>
  2. <div>{{ name }}</div>
  3. </template>
  4. <script setup>
  5. import { storeA } from '@/piniaStore/storeA'
  6. let piniaStoreA = storeA()
  7. let { piniaMsg, name } = piniaStoreA
  8. piniaStoreA.$patch({
  9. name: 'daming'
  10. })
  11.  
  12. </script>

浏览器展示如下

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

为了解决这个问题,Pinia提供了一个结构方法storeToRefs,我们将组件App.vue使用storeToRefs解构

  1. <template>
  2. <div>{{ name }}</div>
  3. </template>
  4. <script setup>
  5. import { storeA } from '@/piniaStore/storeA'
  6. import { storeToRefs } from 'pinia'
  7. let piniaStoreA = storeA()
  8. let { piniaMsg, name } = storeToRefs(piniaStoreA)
  9. piniaStoreA.$patch({
  10. name: 'daming'
  11. })
  12.  
  13. </script>

再看下页面变化

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

getters

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

Pinia

我们先将piniaStore/storeA.js改为

  1. import { defineStore } from "pinia";
  2.  
  3. export const storeA = defineStore("storeA", {
  4. state: () => {
  5. return {
  6. count1: 1,
  7. count2: 2,
  8. };
  9. },
  10. getters: {
  11. sum() {
  12. console.log('我被调用了!')
  13. return this.count1 + this.count2;
  14. },
  15. },
  16. });

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

  1. <template>
  2. <div>{{ piniaStoreA.sum }}</div>
  3. </template>
  4. <script setup>
  5. import { storeA } from '@/piniaStore/storeA'
  6. let piniaStoreA = storeA()
  7. console.log(piniaStoreA.sum) //3
  8.  
  9. </script>

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

  1. import { storeA } from '@/piniaStore/storeA'
  2. let piniaStoreA = storeA()
  3. console.log(piniaStoreA.sum)
  4. console.log(piniaStoreA.sum)
  5. console.log(piniaStoreA.sum)
  6. piniaStoreA.count1 = 2
  7. console.log(piniaStoreA.sum)

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

Vuex

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

  1. import { createStore } from "vuex";
  2.  
  3. export default createStore({
  4. strict: true,
  5. //全局state,类似于vue种的data
  6. state: {
  7. count1: 1,
  8. count2: 2,
  9. },
  10.  
  11. //类似于vue中的计算属性
  12. getters: {
  13. sum(state){
  14. return state.count1 + state.count2
  15. }
  16. }
  17.  
  18.  
  19. });

modules

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

Pinia

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

  1. import { defineStore } from "pinia";
  2.  
  3. export const storeA = defineStore("storeA", {...});
  4. export const storeB = defineStore("storeB", {...});
  5. export const storeC = defineStore("storeB", {...});

Vuex

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

  1. import { createStore } from "vuex";
  2. const moduleA = {
  3. state: () => ({
  4. count:1
  5. }),
  6. mutations: {
  7. setCount(state, data) {
  8. state.count = data;
  9. },
  10. },
  11. actions: {
  12. getuser() {
  13. //do something
  14. },
  15. },
  16. getters: { ... }
  17. }
  18.  
  19. const moduleB = {
  20. state: () => ({ ... }),
  21. mutations: { ... },
  22. actions: { ... }
  23. }
  24.  
  25. export default createStore({
  26. strict: true,
  27. //全局state,类似于vue种的data
  28. state() {
  29. return {
  30. vuexmsg: "hello vuex",
  31. name: "xiaoyue",
  32. };
  33. },
  34. modules: {
  35. moduleA,
  36. moduleB
  37. },
  38. });

使用moduleA

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

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

  1. const moduleA = {
  2. namespaced: true,
  3. state: () => ({
  4. count: 1,
  5. }),
  6. mutations: {
  7. setCount(state, data) {
  8. state.count = data;
  9. },
  10. },
  11. actions: {
  12. getuser() {
  13. //do something
  14. },
  15. },
  16. }

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

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

写在最后

通过以上案例我们会发现Pinia比Vuex简洁许多,所以如果我们的项目是新项目的话建议使用Pinia。 当然如果我们的项目体量不是很大,我们其实没必要引入vue的状态管理库,盲目的使用反而会徒增心智负担。

到此这篇关于一文详解Pinia和Vuex与两个Vue状态管理模式的文章就介绍到这了,更多相关Vue状态管理模式内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号