【发布时间】:2019-09-17 11:56:10
【问题描述】:
在 main.ts 中:
Vue.prototype.$http = http
然后在另一个组件中,在一个类中我不能调用this.$http。我已经阅读了有关增强类型的信息,但不知道将文件放在哪里,如何调用它,关于这个主题的文档不是很清楚:https://vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins
所以我创建了一个文件'src/types/vue.d.ts':
import Vue from 'vue'
import http from '@/http'
declare module 'vue/types/vue' {
interface Vue {
$http: http
}
}
http.ts 的内容:
import axios from 'axios'
const HTTP = axios.create({
baseURL: process.env.VUE_APP_API_URL
})
export default {
login(credentials: any) {
return HTTP.post('/auth', {
account_email: credentials.email,
account_password: credentials.password
})
}
}
但我仍然不能在组件中使用this.$http。我的目标是在每个组件中全局使用 this.$http 引用 http.ts(此处为 axios 模块)。
【问题讨论】:
-
但是为什么要扩充 Vue 类型呢?每个组件都需要http函数吗?您可以为 http 调用创建一个辅助类...
-
@Kokodoko,几乎每个组件都需要
$http,在每个组件中都导入它很烦人。 -
那些减去我的人,请解释你为什么这样做。
标签: typescript vue.js