Vuex 和 Pinia 都是 Vue.js 的状态管理库,但它们在设计理念、使用方式和功能特性上有一些区别。以下是它们的主要区别:
Vuex:
state(状态)、mutations(同步更新状态)、actions(异步操作)、getters(派生状态)和 modules(模块化)。Pinia:
store,每个 store 是一个独立的状态管理单元,包含 state、actions 和 getters。Vuex:
mapState、mapGetters、mapActions 等辅助函数来简化状态管理。mutations 来更新状态,actions 用于异步操作。// store.js
import { createStore } from 'vuex';
export default createStore({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
},
},
getters: {
doubleCount(state) {
return state.count * 2;
},
},
});
Pinia:
defineStore 定义状态管理单元,语法更加简洁。mutations,直接通过 actions 更新状态。// store.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
incrementAsync() {
setTimeout(() => {
this.increment();
}, 1000);
},
},
getters: {
doubleCount: (state) => state.count * 2,
},
});
Vuex:
state、mutations、actions 和 getters。Pinia:
Vuex:
Pinia:
Vuex:
Pinia:
希望这些信息对你有所帮助!
热门推荐:
0