首页 > 解决方案 > 访问服务内部的 Vue 商店

问题描述

我对 Vue 有点陌生,正在尝试将我的逻辑放入商店,以便我可以在整个应用程序的多个组件中使用它。我创建了一个leads.module.js调用我的文件的leads.service.js文件。

    import LeadsService from "../../services/leads.service";

    const state =  {
      leadsOverTime: {}
    }

    const actions = {
      async leadsOverTime({ commit }, group_by = '') {

        const response = await LeadsService.leadsOverTime(group_by);
        commit('leadsOverTime', response)
        return true

      },
    };

    const mutations = {
      leadsOverTime(state, data) {
        state.leadsOverTime = data;
      },
    };

    export const leads = {
      namespaced: true,
      state,
      actions,
      mutations,
    }

此文件由我的根存储导入,其中包含我在服务中需要的状态值:

    const state = {
        startDate        : moment().startOf('year').format(),
        endDate          : moment().format(),
        selectedLocations: [],

    }

    export default new Vuex.Store({
        modules: {
          leads: leads
        },
        state,
        strict: process.env.NODE_ENV !== 'production'
    })

最后,我的服务使用这些状态变量进行 API 调用:

    import axios from "../axios";
    import {store} from "../store/store"

    const LeadsService = {
      leadsOverTime: async function(group_by = '') {
        await axios.get(
          `/dashboards/potential_clients.json?
            &start_date=${ store.state.startDate }
            &end_date=${ store.state.endDate }
            &location_ids=${ this.selectedLocations }
            &compare=year
            &group_by=${group_by}`)
          .then( response => {
            return response
          })
          .catch( error => {
            console.log(error)
          })
      }
    };

    export default LeadsService
    export { LeadsService }

我认为这会起作用,但我收到一个错误:

Uncaught (in promise) TypeError: Cannot read property 'state' of undefined

我还应该如何访问服务中的这些变量?根存储已导入我的main.js文件中,该文件应在从我的组件中调用我的服务之前加载。我错过了什么?可能值得注意的是,在我的日志中我看到:"export 'store' was not found in '../store/store'.

标签: vue.js

解决方案


代码没有问题。可能是导致问题的导入store。如果您要导出storeas const,那么您可以像这样导入它

// your store file
export const store = new Vuex.Store({
    modules: {
      // your modules
    },
});

// importing store to other files
import {store} from "../store/store"

否则你可以简单地导入

import store from "../store/store"

推荐阅读