Vue 2.7 組合 API + Vuex
P粉295728625
P粉295728625 2023-11-03 10:06:49
0
1
731

我們正在嘗試將 Vue 2 應用程式遷移到 Vue 2.7,但在組合 API 和 Vuex 方面遇到了一些問題。

在我們目前的應用程式中,我們使用 @vue/composition-api 套件來讓我們使用可組合項。在這些可組合項中,我們需要訪問商店,並像這樣獲取它:

...rest of the component
setup(props, { parent }) {
  const store = parent.$store
  someComposable({ store })
}

但是,當我們將 Vue 版本升級到 2.7 時,不再支援此語法。我們需要使用 Vuex 中的 useStore 可組合項目來存取商店。這僅適用於 Vuex 版本 4。

在目前版本的 Vue 上升級 Vuex 版本 4 時,我們看到以下錯誤:

WARNING in ./node_modules/vuex/dist/vuex.esm-bundler.js 14:9-15
 export 'inject' (imported as 'inject') was not found in 'vue' (possible exports: default)
  @ ./src/plugins/vuex.js 4:0-24 5:8-12
  @ ./src/app.js 11:0-24

 WARNING in ./node_modules/vuex/dist/vuex.esm-bundler.js 132:14-25
 export 'effectScope' (imported as 'effectScope') was not found in 'vue' (possible exports: default)
  @ ./src/plugins/vuex.js 4:0-24 5:8-12
  @ ./src/app.js 11:0-24

 WARNING in ./node_modules/vuex/dist/vuex.esm-bundler.js 140:27-35
 export 'computed' (imported as 'computed') was not found in 'vue' (possible exports: default)
  @ ./src/plugins/vuex.js 4:0-24 5:8-12
  @ ./src/app.js 11:0-24

 WARNING in ./node_modules/vuex/dist/vuex.esm-bundler.js 148:17-25
 export 'reactive' (imported as 'reactive') was not found in 'vue' (possible exports: default)
  @ ./src/plugins/vuex.js 4:0-24 5:8-12
  @ ./src/app.js 11:0-24

 WARNING in ./node_modules/vuex/dist/vuex.esm-bundler.js 362:2-7
 export 'watch' (imported as 'watch') was not found in 'vue' (possible exports: default)
  @ ./src/plugins/vuex.js 4:0-24 5:8-12
  @ ./src/app.js 11:0-24

 WARNING in ./node_modules/vuex/dist/vuex.esm-bundler.js 1101:9-14
 export 'watch' (imported as 'watch') was not found in 'vue' (possible exports: default)
  @ ./src/plugins/vuex.js 4:0-24 5:8-12
  @ ./src/app.js 11:0-24

這是有道理的,因為它們是組合 API 的一部分,並且在我們使用的 Vue 版本 (2.6.14) 上不可用。但 Vuex 版本 4 和 Vue 版本 2.7 似乎也不能一起工作。

當我們使用 Vuex ^4.1.0 和 Vue 2.7.13 運行應用程式時,我們會看到以下錯誤:

[Vue warn]: Error in render: "TypeError: this.$store is undefined"

我們如何讓 Vue 2.7 與 Vuex 和組合 API 一起運作?具體來說,我們如何在 Vue 2.7 上的可組合項中存取 Vuex 儲存?

P粉295728625
P粉295728625

全部回覆(1)
P粉162773626

在您的商店中:

const store = new Vuex.Store({ ...options })
export default store;
export const useStore = () => store

在任何元件中,包含子元件:

setup() {
  const store = useStore();
  // ...
}

如果您有多個商店,請相應地命名商店及其use功能。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!