Vue 2.7 With Composition 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和Vue2.7.13运行应用程序时,我们会看到以下错误:

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

如何让Vue 2.7与Vuex和API组合一起工作?具体来说,我们如何在Vue 2.7上的可堆肥产品中访问Vuex商店

在您的商店中:

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

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

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

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

最新更新