vue3 pinia 和 vuex的对比
作者:互联网
前言
vue3中使用了全新的组合式API: https://v3.cn.vuejs.org/
vuex从4.x版本开始也对应的提供了适配vue3的api:https://vuex.vuejs.org/zh/
pinia是新出现的状态管理工具,相对于vuex更加精简: https://pinia.vuejs.org/
pinia
注意:
- pinia 合并了 mutation 和 action,包括异步
- 无需通过mutation修改state,store.count++可以直接修改状态
// 导入pinia
import { createPinia } from 'pinia';
const pinia = createPinia();
let app = createApp(App);
app.use(pinia);
// 正文,主模块
import { defineStore } from 'pinia';
const useMainStore = defineStore('main', {
state: () => {
return {
test: null,
}
},
actions: {
changeTest() {
},
async getTest() {
// await
}
},
getters: {
}
})
// 其他模块
const useChildStore = defineStore('child', {
state: () => {
return {
testChild: null,
}
},
actions: {
changeTestChild() {
},
async getTestChild() {
// await
}
},
getters: {
}
})
// 使用
import { useMainStore } from '@/store';
const store = useMainStore();
store.setLang(lang); // store.lang = lange;
const { lang } = toRefs(store);
vuex
注意:
- mutations中必须是同步函数
- Action 类似于 mutation,区别是action提交mutation,且action可以异步
// 导入vuex
import { createApp } from 'vue';
import store from '@/store';
app = createApp(App);
app.use(store);
// 正文
const store = createStore({
state: {
count: 1,
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos (state) {
return state.todos.filter(todo => todo.done)
}
},
mutations: {
increment (state, payload) {
state.count += payload.amount; // store.commit('increment', {amount: 10})
}
},
actions: {
increment (context) {
context.commit('increment'); // store.dispatch('increment')
},
async actionB ({ dispatch, commit }, { param }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
},
modules: {
child: childModule,
}
})
// 子模块
const childModule = createStore({
// 命名空间,防止同名时出错
namespaced: true,
state: initialState,
mutations,
actions,
getters,
})
// 使用
import store from '@/store';
store.commit('setLang', lang);
// 使用2
import { useStore } from 'vuex';
const store = useStore();
const { lang } = toRefs(store.state);
标签:const,state,pinia,vue3,import,vuex,store 来源: https://www.cnblogs.com/nangezi/p/16437877.html