Pinia和Vuex都是 Vue 状态管理库。但它们还是存在一些区别。
1.开发背景
1)Vuex:Vuex 是 Vue.js 官方推出的状态管理库,主要用于管理复杂应用中的全局状态。它在 Vue 2 和 Vue 3 中都被广泛使用。
2)Pinia:Pinia 是一个社区驱动的状态管理库,最初是为了弥补 Vuex 在某些场景下的不足而创建的。现在,它已经被 Vue 官方认可,并成为 Vue 3 推荐的状态管理库之一。
2.API
1)Vuex
使用 store 对象来管理状态。
通过 mapState、mapActions 等辅助函数来映射状态和操作。
使用 mutations 进行同步状态更新,actions 进行异步操作。
支持模块化,通过 modules 选项可以将状态分割成多个模块。
2)Pinia
引入了 Store 的概念,每个 Store 是一个独立的状态管理单元。
使用 defineStore 定义 Store,支持直接在 Store 中定义状态、 getters 和 actions。
状态更新可以直接在 actions 中进行,无需区分 mutations 和 actions。
同样支持模块化,但通过 Store 的组合来实现更灵活的状态管理。
3.使用方式
Vuex的使用方式
javascript
//store/index.js
import { createStore } from 'vuex';
const store = createStore({
state() {
return { count: 0 };
},
// 定义Getter
getters: {
evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd'
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
incrementIfOdd(context) {
context.commit('increment');
}
}
});
使用store,创建一个StoreUsed.vue组件
xml
<template>
<div>
<p>Count: {{ count }}</p>
<p>Even or Odd? {{ evenOrOdd }}</p>
<button @click="increment">Increment</button>
<button @click="incrementIfOdd">incrementIfOdd</button> </div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count
},
evenOrOdd () {
return this.$store.getters.evenOrOdd
}
},
methods: {
increment() {
this.$store.commit('increment')
},
incrementIfOdd () {
this.$store.dispatch('incrementIfOdd')
}
}
}
</script>
Pinia的使用方式
创建 store/index.js 文件
javascript
import { defineStore } from "pinia"
// defineStore(当前 store 的 Id, {配置项})
export const useCountStore = defineStore("count", {
// 状态
state: () => {
return {
count: 1
}
},
// 计算属性
getters: {
// 这里的计算属性使用时,为一个属性而不是方法
increaseNum(store) {
return store.count * 10
}
},
// 方法
actions: {
addCount(value) {
this.count += value
}
}
})
在 main.js 中引入
javascript
// 这是 Vue3 的引入方式,Vue2 不太一样
import { createApp } from "vue";
import App from "./App.vue";
import { createPinia } from "pinia";
const app = createApp(App);
app.use(createPinia());
app.mount("#app");
pinia基本使用
xml
<script setup>
import { useCountStore } from "../store/index.js";
// 可以直接通过 store. 去获取 state、getters、actions 中的属性和方法了
const countStore = useCountStore();
// 直接获取
countStore.count // 1
// 计算属性获取
countStore.increaseNum // 10
// 修改状态1
countStore.count += 1
// 修改状态2
countStore.addCount(1)
// 修改状态3,这种方式和 React 中的 setState 很像
countStore.$patch({
count: countStore.count + 1
})
// 修改状态4
countStore.$patch((state) => {
state.count += 1
})
// 替换状态(不是覆盖状态),需要新的状态去替换旧的,如果 key 值不相同就是添加新状态
countStore.$state = {count: 2}
// 重置状态
countStore.$reset()
// store 中的值,每修改一次就会触发
countStore.$subscribe(({ events, storeId, type }, state) => {
// 里面包含了一些信息
events
// 这个 store 的 Id,这里是 count
storeId
/*
修改值的方式:
'direct':直接修改、使用 action 中的方式修改
'patch object':使用 $patch({}) 修改
'patch function':使用 $patch((state)=>{}) 修改、使用 $state 替换、$reset()重置
*/
type
});
// action 中的函数每次调用,都会触发一次
countStore.$onAction(({ args, name, store, after, onError }) => {
// 调用 actions 中函数的传参列表
args
// 函数名称
name
// store 对象
store
// 当函数正常执行完成后执行
// result 接收函数返回成功状态的 Promise
after((result) => {
console.log(result);
});
// 当函数中存在失败状态的 Promise,或函数抛出异常时执行
onError((err) => {
console.log(err);
});
});
</script>