vue.js - 在 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,但即使在查看文档后我仍然不确定如何实现它。
任何投入将不胜感激。谢谢!
解决方案
创建一个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,主要在“操作”中使用它可能很有用。
推荐阅读
- asp.net-mvc - 如何在 Asp.Net Core MVC 中重置密码之前验证用户令牌是否有效?
- amazon-web-services - 连接到 EC2 实例上的 redis 时连接被拒绝
- c# - 使用 unity 2017 时的一般/未知 HTTP 错误
- bash - 如何在 sed 命令中动态传递变量
- database - 无法在 MongoDB 中使用聚合函数
- java - opencv MatOfPoint2f 按x坐标排序
- typescript - 如何使用代理方法扩展超级代理?
- reactjs - React TypeScript将函数传递给子组件
- r - 使用 data.table 为行块创建组标签
- javascript - 如何禁用 sap.m.Table 上的繁忙指示器?