vuex和Pinia的区别

Pinia API 与 Vuex(<=4) 也有很多不同,即:

1、mutation 已被弃用。它们经常被认为是极其冗余的。它们初衷是带来 devtools 的集成方案,但这已不再是一个问题了。

2、无需要创建自定义的复杂包装器来支持 TypeScript,一切都可标注类型,API 的设计方式是尽可能地利用 TS 类型推理。

3、无过多的魔法字符串注入,只需要导入函数并调用它们,然后享受自动补全的乐趣就好。

4、无需要动态添加 Store,它们默认都是动态的,甚至你可能都不会注意到这点。注意,你仍然可以在任何时候手动使用一个 Store 来注册它,但因为它是自动的,所以你不需要担心它。

5、不再有嵌套结构的模块。你仍然可以通过导入和使用另一个 Store 来隐含地嵌套 stores 空间。虽然 Pinia 从设计上提供的是一个扁平的结构,但仍然能够在 Store 之间进行交叉组合。你甚至可以让 Stores 有循环依赖关系。

6、不再有可命名的模块。考虑到 Store 的扁平架构,Store 的命名取决于它们的定义方式,你甚至可以说所有 Store 都应该命名。

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

import { defineStore } from "pinia";

export const storeA = defineStore("storeA", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
    };
  },
  getters: {},
  actions: {},
});
2.修改状态
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
1.直接修改

相比于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>
2.patch方法可以修改多个state中的值,

在他的实例上有$patch方法可以批量修改多个值

$patch({修改的属性1:值,修改的属性2:值})

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'
})
3、$patch批量修改函数形式

推荐使用函数形式 可以自定义修改逻辑

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

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

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

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

定义Actions

在actions 中直接使用this就可以指到state里面的值

actions: {
        //定义actions
        setCurrent() {
            this.current ++
        }
    }


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')
5.通过原始对象修改整个实例

$state您可以通过将store的属性设置为新对象来替换store的整个状态

缺点就是必须修改整个对象的所有属性

<template>
  <!-- 3、使用仓库中的数据 -->
  <div>
    <span> {{ testStore.current }}====={{ testStore.name }} </span>
    <br />
    <button @click="changeCurrent">修改current</button>
  </div>
</template>
<script lang="ts">
import { defineComponent } from "vue";

import { Test } from "./store";
export default defineComponent({
  setup() {
    let testStore = Test();
    function changeCurrent() {
      //1、直接修改
      //   testStore.current++;
      //2、$patch 批量修改  $patch({修改的属性1:值,修改的属性2:值})
      //   testStore.$patch({
      //     current: 99,
      //     name: "娃娃",
      //   });

      //3、使用$patch(函数形式触发)
      //   testStore.$patch((state) => {
      //     state.current++;
      //     state.name += "~";
      //   });

      // 4、原始的$state对象操作,缺点,state中所有的熟悉必须全部修改
      testStore.$state = {
        current: 999,
        name: "范冰冰",
      };
    }

    return {
      testStore,
      changeCurrent,
    };
  },
});
</script>
6.重置state

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

import { storeA } from '@/piniaStore/storeA' 
let piniaStoreA = storeA()
piniaStoreA.$reset()
3.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>//无变化

为了解决这个问题,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>

 

4.getters

其实Vuex中的getters和Pinia中的getters用法是一致的,用于自动监听对应state的变化,从而动态计算返回值(和vue中的计算属性差不多),并且getters的值也具有缓存特性,可以在不修改state值的情况下 对值进行一些操作

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


});

 

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

  • 28
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值