首页 > 解决方案 > 在 Vue JS 中,如何使我的 APIService.js 类对组件全局可用,而不需要单独的组件导入它?

问题描述

几乎我的所有组件都需要与我的 apiservice.js 类进行某种交互,该类导入 Axios 并根据调用的方法发出适当的 http 请求。我知道通常不建议这样做,但是,在我的每个组件中,我都有以下内容:

import {APIService} from '../store/APIService.js';
const apiService = new APIService();

我的 APIService.js 看起来大致是这样的(为简单起见进行了修剪):

import axios from 'axios';
const API_URL = 'http://myserver:82/services/locationmanagement';

export class APIService{

constructor(){
}

getLocations() {
    const url = `${API_URL}/api/locations/`;
    return axios.get(url).then(response => response.data);
}

saveLocation(location) {
    let url = `${API_URL}/api/locations/`;
    let id = location.id;
    let httpMethod = 'post';

    if(id > 0 ) {
        httpMethod = 'put';
        url = `${API_URL}/api/locations/${id}`;
    }

    let options = {
        method: httpMethod,
        url: url,
        headers: { 'Content-Type': 'application/json' },
        data: location
    }

    return axios(options);
   }

}   

我希望它以某种方式可用于全局 Vue 实例,并且我的组件可以以某种方式访问​​它。

我相信这需要在我的main.js文件中以某种形式实现,可能通过 Vue.use,但即使在查看文档后我仍然不确定如何实现它。

任何投入将不胜感激。谢谢!

标签: vue.jsbabeljs

解决方案


创建一个Vuejs 插件,将其导入main.js,并在其中调用它Vue.use(myservice)

编辑:

根据评论,一种方法是将插件添加到 Vue 原型中。例如,一个 axios 包装器可以定义为

import axios from 'axios'

export default {

  install:function(Vue,options) {

    Vue.prototype.$dataservice = axios.create({...})
    ...

然后它可以像其他全局 vue 函数一样从组件中调用,例如$refs, $set, $emit:

 ...
 this.$dataservice.get(...)
 // or
 this.$dataservice.post(...)
 ...

使用数据服务 api,如果使用 Vuex,主要在“操作”中使用它可能很有用。


推荐阅读