Vuex 4 已正式釋出,此版本的更新重點是提供更好的相容性。從 release note 可以看到,Vuex 4 不但支援 Vue 3,並且提供與 Vuex 3 完全相同的 API,因此使用者可以在 Vue 3 中重用其現有的 Vuex 程式碼。
雖然 Vuex 4 將相容性放在了首位,但此版本依舊包括部分破壞性變化,下邊簡單介紹一下。
安裝過程已更改為了與新的 Vue 3 初始化過程保持一致,Vuex 的安裝過程已更改。舉個例子,如果需要建立一個新的 store 例項,現在會鼓勵使用者使用新引入的createStore功能。
import { createStore } from 'vuex'export const store = createStore({ state() { return { count: 1 } }})
儘管從技術上來講這並不是一個破壞性變化,開發者仍可以使用new Store(...)語法,但官方表示建議將該方法與 Vue 3 和 Vue Router 4 保持一致。
要將 Vuex 安裝到一個 Vue 例項,需要傳遞例項而非 Vuex。
import { createApp } from 'vue'import { store } from './store'import App from './App.vue'const app = createApp(App)app.use(store)app.mount('#app')
打包與 Vue 3 一致
新版本會生成以下的包,以與 Vue 3 打包保持一致:
vuex.global(.prod).jsvuex.esm-browser(.prod).jsvuex.esm-bundler.jsvuex.cjs.jsComponentCustomProperties型別化Vuex 4 刪除其this.$store在 Vue Component 中的全域性型別以解決 issue #994。與 TypeScript 一起使用時,必須宣告自己的模組擴充 (module augmentation)。
將以下程式碼放在專案中以允許this.$store正確型別化:
// vuex-shim.d.tsimport { ComponentCustomProperties } from 'vue'import { Store } from 'vuex'declare module '@vue/runtime-core' { // Declare your own store states. interface State { count: number } interface ComponentCustomProperties { $store: Store<State> }}
從核心模組匯出createLogger 函式在 Vuex 3 中,createLogger函式從vuex/dist/logger中匯出,但現在它已包含在核心軟體包中。因此應該直接從vuex包中匯入。
import { createLogger } from 'vuex'
此外還包括兩個 Bugfix:
修復匯出缺少storeKey的錯誤(4ab2947)修復 webpack 包中的 tree shaking 無法執行的錯誤 (#1906) (#1907) (aeddf7a)下載地址:https://github.com/vuejs/vuex/releases/tag/v4.0.0
最新評論