首页  >  问答  >  正文

Vue 2.7 组合 API + Vuex

我们正在尝试将 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粉295728625P粉295728625351 天前837

全部回复(1)我来回复

  • P粉162773626

    P粉1627736262023-11-04 00:54:16

    在您的商店中:

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

    在任何组件中,包括子组件:

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

    如果您有多个商店,请相应地命名商店及其use功能。

    回复
    0
  • 取消回复