我用TS语法创建的vue项目,封装了axios模块,取名叫http
在main.ts中引入
import http from "./http/http"
Vue.prototype.http = http;
然后我在组件中引用出错
ERROR in F:/daimaku2/tsqianduan/src/App.vue(54,12):
54:12 Property 'http' does not exist on type 'CombinedVueInstance<Vue, { tupian: string; }, { huoqudingtu(): void; }, unknown, Readonly<Record<never, any>>>'.
52 | window.console.log("开始获取");
53 | const that2 = this;
> 54 | this.http
| ^
55 | .get("/dingtu/")
56 | .then(function(value: any) {
57 | window.console.log(JSON.parse(value.data));
Version: typescript 3.7.5
Time: 1607ms
参考GPT和自己的思路:
根据错误提示信息,可以看出是在组件中引用http模块时,没有正确地声明http模块的类型,导致编译器不识别该模块的方法和属性,进而报出了错误。
解决方法如下:
在组件中,需要声明一个接口,来指定组件实例中http模块的类型。代码如下:
import { Vue } from "vue-property-decorator";
import http from "@/http/http";
declare module "vue/types/vue" {
interface Vue {
http: typeof http;
}
}
这段代码声明了一个Vue模块的类型,其中声明了一个名为"Vue"的接口,用来扩展Vue模块。在该接口中,声明了http模块的类型为typeof http
,也就是http模块的类型与http.ts中导出的类型一致。
这样,在组件中就可以正常地使用http模块了。