typescript - Vue.prototype.$property 不适用于 Typescript
问题描述
在 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 3 答案
增强 Vue 以支持您的自定义组件属性是通过模块扩充完成的。要添加您的$http
声明并支持它,您可以创建vue-shim.d.ts
文件并扩充vue/runtime-core
import axios from 'axios'
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$http: typeof axios
}
}
Vue 还断言,对于版本 3,您必须将其导入或导出为文件中的顶级代码行,ts
以确保将其视为模块:
确保声明文件是 TypeScript 模块 为了利用模块扩充,您需要确保文件中至少有一个顶级导入或导出,即使它只是 export {}。
现在,当您安装自定义插件时,您可以将其挂在app.config.globalProperties
对象上:
// my-custom-plugin.js
import axios from 'axios'
import http from 'plugins/http'
export default {
install (app, options) {
app.config.globalProperties.$http = http
}
}
有关 Vue 2 的答案,请参见下文。
Vue 2 答案
您不能将 的类型声明$http
为值,而是进行新的输入:
// http.d.ts
export default interface {
login(credentials: any): PromiseLike<any>
}
然后将其用作您的打字声明:
import http from '@/types/http'
...
interface Vue {
$http: http
}
现在http.ts
按照上面评论中的链接进行操作:
import _Vue from 'vue'
import axios from 'axios'
const http = {
login(credentials: any) {
return HTTP.post('/auth', {
account_email: credentials.email,
account_password: credentials.password
})
}
}
export function http(Vue: typeof _Vue): void {
Vue.prototype.$http = http;
}
现在您需要导入该http.ts
文件并将Vue.use
其导入main.ts
import Http from '@/http'
Vue.use(Http)
现在您的组件可以使用您的 http 插件:
mounted() {
this.$http.login(credentials)
.then((response) => console.log(response))
.catch((error) => console.warn(error))
}
推荐阅读
- java - 为什么要添加方法连接 arrList 的元素?
- ansible - Ansible 解析结果注册 var 中的特定行
- r - 从 JSON 格式检索数据的正则表达式模式,由于不够具体,需要太多时间
- ios - 堆栈视图和内容拥抱优先级 - 意外行为
- .net - 在 Azure DevOps 上的 .Net Core 应用程序上构建管道期间发布时出现 NPM 错误
- wordpress - 如何将谷歌分析用于 wordpress 插件?
- amazon-web-services - AWS LoadBalancer CNAME 隐藏
- express - 我应该使用快速路由参数来选择要运行的回调,还是应该明确声明路由和回调?
- c# - 沿 z 轴缓慢旋转对象
- excel - Copy the last 5 cells in a column until last row