如何在NuxtJS的我的​​服务文件夹中访问此文件

时间:2020-01-27 11:44:39

标签: javascript vue.js nuxt.js

你好,我在VueMastery中学习了NuxtJS,我认为他们教的东西真的很好。获取数据的方式包括异步获取,存储和服务。

page / index.vue

<template>
  <div></div>
</template>

<script>
export default {
  mounted() {
    this.$myInjectedFunction("works in mounted");
  },
  async fetch({ store, app, req, env }) {
    await store.dispatch("scooby/getBanners", { page: 1 });
  }
};
</script>

store / scooby.js

import ScoobyService from "@/services/ScoobyService.js";
export const state = () => ({
  banners: []
});
export const mutations = {
  SET_BANNERS(state, banners) {
    state.banners = banners;
  }
};
export const actions = {
  getBanners({ commit }, payload) {
    this.$myInjectedFunction("accessible in actions");
    const type = payload.type || 1;
    const params = `?ad_type=${type}&page=${payload.page}`;
    return ScoobyService.adBanner(params).then(response => {
      commit("SET_BANNERS", response.data);
    });
  }
};

services / scoobyService.js

/* eslint-disable no-console */
import { scoobyApiClient, scoobyRequestSetup } from "@/assets/js/axios.js";

const apiModule = "scooby";

const resources = {
  adBanner: `/v1/member/banners`
};

export default {
  adBanner(getParams) {
    // this.$myInjectedFunction("accessible in actions");
    const body = {};
    const resource = `${resources.adBanner}/${getParams}`;
    const [api, req] = scoobyRequestSetup(resource, body, apiModule);

    return process.server
      ? scoobyApiClient.get(api, req)
      : scoobyApiClient.post(api, req);
  }
};

plugins / combined-inject.js

/* eslint-disable no-console */
export default ({ app }, inject) => {
  inject("myInjectedFunction", string => console.log("That was easy!", string));
};

nuxt.config.js

module.exports = {
  ...
    plugins: [
    "~/plugins/axios.js"
  ],
  ...
}

services / scoobyService.js 无法访问this对象,但 store / scooby.js 可以访问。如何在 services / scoobyService.js

中访问此对象

2 个答案:

答案 0 :(得分:2)

您注入的功能仅在有效的Vue实例中可用,而scoobyService.js则不可用(请参见:Vue instance properties)。您也可以将函数作为导出单独显示,并在服务中以这种方式使用。

export const myInjectedFunction = string => console.log("That was easy!", string);
export default ({ app }, inject) => {
  inject("myInjectedFunction", myInjectedFunction );
};

然后,只要您想在Vue实例之外使用它,就分别导入该功能

答案 1 :(得分:2)

您应按如下所示创建文件,然后可以使用this.$customService

访问服务方法

services / CustomService.js

export default {
  hello() {
    return 'Hello'
  },
  bye() {
    return 'Bye'
  }
}

plugins / combined-inject.js

import Vue from 'vue'
import ServiceOnefrom '../services/ServiceOne'
Vue.prototype.$ServiceOne= ServiceOne

// or

// import ServiceOne from '../services/ServiceOne'
// export default ({ app }, inject) => {
//  inject("serviceOne", ServiceOne);
// };