访问服务内部的Vue商店

时间:2020-04-01 12:53:15

标签: vue.js

我对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'

2 个答案:

答案 0 :(得分:0)

代码没有问题。可能是由于导入store而引起的。如果您将store导出为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"

答案 1 :(得分:0)

无需导入整个商店。 U可以使用上下文在调用“ leadsOverTime”中传递必要的变量。

不能在操作中直接访问状态变量,因此请使用上下文来访问状态变量。

您也可以调用“ context.commit”来进行突变

纠正我,如果有错,我是vue的新手

const actions = {
  async leadsOverTime( context , group_by = '') {
    const response = await LeadsService.leadsOverTime(group_by,context.state);
    context.commit('leadsOverTime', response)
    return true
  },
};