模块定义
- Vuex:模块定义相对复杂,每个模块需要通过
export default
导出一个包含state
、mutations
、actions
等属性的对象。模块之间的嵌套需要通过在父模块的modules
属性中进行配置。例如:
// moduleA.js
export default {
state: () => ({
count: 0
}),
mutations: {
increment(state) {
state.count++;
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
}
}
};
// store.js
import Vue from 'vue';
import Vuex from 'vuex';
import moduleA from './moduleA';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
moduleA
}
});
- Pinia:模块定义更简洁直观,通过
defineStore
函数创建一个store,不需要像Vuex那样进行复杂的模块嵌套配置。例如:
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
}
});
数据更新机制
- Vuex:数据更新遵循严格的单向数据流,通过提交
mutations
来修改state
,mutations
必须是同步函数。如果需要异步操作,要在actions
中通过commit
触发mutations
。例如:
// 在组件中
this.$store.commit('increment');
// 或者异步
this.$store.dispatch('incrementAsync');
- Pinia:没有严格区分同步和异步操作,在
actions
中可以直接修改state
,也可以进行异步操作。例如:
// 在组件中
const counterStore = useCounterStore();
counterStore.increment();
// 异步操作
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
async incrementAsync() {
await new Promise(resolve => setTimeout(resolve, 1000));
this.count++;
}
}
});
插件与扩展
- Vuex:插件机制比较成熟,通过
Vuex.Store
的plugins
选项可以添加插件,用于实现如日志记录、持久化等功能。例如:
const myPlugin = store => {
store.subscribe((mutation, state) => {
console.log(mutation.type, state);
});
};
export default new Vuex.Store({
plugins: [myPlugin]
});
- Pinia:插件机制相对较新,通过
pinia.use
可以注册插件。例如:
import { pinia } from './main';
pinia.use(({ store }) => {
store.$subscribe((mutation, state) => {
console.log(mutation.type, state);
});
});
开发体验
- Vuex:由于其严格的规则和较多的概念(如
mutations
、actions
、getters
等),对于初学者可能学习成本较高。
- Pinia:语法更简洁,开发体验更友好,尤其是对于熟悉Composition API的开发者,更易上手和维护。