前言
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);