兩者核心區別就是類型提示,像定義組件需要 defineComponent 同出一轍:
Vue3
import { createStore } from "vuex";
import example from './modules/example'
export default createStore({
state: {},
mutations: {},
actions: {},
modules: { example }
})
1
2
Vue2
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {}
});
1
2
3
我們以 JavaScript 開發為前提,通過如上對比我們發現為了獲取類型提示 Vuex 提供了 createStore() 函數,相當於原來的 Vuex 實例化過程,與 Vue 3 的函數 application 思想一致。
除此之外,modules 寫法沒有任何變化,在 modules 中,仍需要沿襲以前 Vue 2 的直接導出方法:
// src/store/modules/example/index.js
export default {
state,
mutations,
actions,
// 模塊化必須,從而形成 dispath('namespace/action') 作用域
namespaced: true
}
1
2
這就導致了在單個 module 中我們不能獲取類型提示,相對乏力,可以考慮使用 TypeScript 改進代碼提示問題:
export default {
state,
mutations,
actions,
namespaced: true
} as Module<object, any>
1
2
3
效果: