首页 > 解决方案 > 从 nuxtjs 中的外部 js 文件访问存储

问题描述

我正在尝试从组件外部的文件访问商店当我搜索此问题时,我看到人们说我应该从我的文件中导入商店,然后我可以访问它,但我无法做到这一点工作

我的商店是这样建造的:

const createStore = () => {
  return new Vuex.Store({
    state: { ... },
    getters: { ... },
    mutations: { ... },
    actions: { ... },
  })
}

我已经尝试将它导入到我的 js 文件中,就像我看到的推荐的那样

import store from '@/store'

有任何想法吗?

标签: vue.jsvuexnuxt.js

解决方案


您可以通过在实例化时注册来导入商店,如下所示:

外部文件some-service.js

export default class SomeService {
  constructor(store) {
    this.store = store
  }
  doStuff() {
    this.store.dispatch('someAction')
  }
}

推荐阅读