Nuxt:无法从 js 文件访问 vuex 存储

Nuxt: Can't access vuex store from js file

我正在使用 Nuxt 中的 Vuex 状态管理创建一个应用程序。问题是我想创建带有函数的 js 文件,我将把它导入到我的 Vue 文件中。我需要在该文件中访问我的商店。

在 functions.js 中,我想使用 import store from "@/store" 导入商店,但 store 给了我空对象。当我执行 import store from "@/store/dice.js" 时,我想访问它 return undefined 并且在控制台中我得到了信息:"export 'default' (imported as '$store') was not found in '~/store/dice'

@/store/index.js 为空。

@/store/dice.js 得到了 Nuxt 教程中的结构:

export const state = () => ({
list: []
})

export const mutations = {
add(state, text) {
state.list.push({
text,
done: false
})
},
remove(state, { todo }) {
state.list.splice(state.list.indexOf(todo), 1)
},
toggle(state, todo) {
todo.done = !todo.done
}
}

有人能帮忙吗?

位于 store 目录中的 Vuex Store 文件将在构建时由 Nuxt 转换为商店实例。

因此您无法将其中的任何文件导入商店外的其他 js 文件。

您必须解决:

  1. 推荐: 将您的 function.js 文件夹添加到您的商店中并在那里使用您的函数(在突变、动作等中调用它们...)
  2. 不推荐:function.js 中调用您的函数时,将您的商店实例作为参数传递,然后您就可以使用它了。