问题

在 vue 中使用 typescript. 在 mian.ts vue 原型绑定属性 Vue.prototype.$axios = axios, 在组件中使用的时候编辑器报错, 但是可以正常运行代码.
![使用报错](https://img-blog.csdnimg.cn/20210301143933192.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMzE0MzE4,size_16,color_FFFFFF,t_70

解决办法

方法1:

指定 this 类型为 any, 但是使用 any 就失去了类型安全保障, 又得不到工具的支持, 写起来也不太雅观.
在这里插入图片描述

方法2:

在组件内申明 $axios: any, 这样每个组件内都需要这样写, 也是很麻烦
在这里插入图片描述
或者
在这里插入图片描述

方法3:

src/shims.d.ts 文件中添加以下代码.

import Vue from 'vue' // 需要在 declare 外引入
declare module 'vue/types/vue' {
	interface Vue {
		$axios: any
	}
}

方法3引出新问题:

这样写虽然解决了当前问题, 但是如果在 shims.d.ts 代码块的外部使用 import 又出现了另外一个问题.
Cannot find module './App.vue' or its corresponding type declarations
在这里插入图片描述

原因:

ts 识别不了 .vue 文件.

解决办法

这个解决办法 就. 就…
在这里插入图片描述

就是 shims.d.ts 中不要在 的外部引入使用 import.
在块外部引入, 又不能解决 ts 找不到原型属性问题.

在这里插入图片描述

方法4: 完美解决

我刚才又试了一下新的方法. 完美解决这个问题 🙄
把方法 3 方法3 的代码写在 main.ts 中即可. 因为 main.ts 中默认引入了vue 就不用再次引入.
在这里插入图片描述

方法5: 完美解决以上两个问题.

2021-03-02 … 更

  1. shims-vue.d.ts 拆分为两个文件.
  2. shimis-vue.d.ts 同级目录新建 vue.d.ts <名字随意, 我是这样定义的>, 代码:
// vue.d.ts 处理 识别 .vue 文件
declare module '*.vue' {
	import Vue from 'vue'
	export default Vue
}
  1. 修改 shims-vue.d.ts 文件代码, 处理其他内容.
import Vue from 'vue'
import { Store } from 'vuex'

declare module 'vue/types/vue' {
	interface Vue {
		$store: Store,
		$axios: any, // 挂载的 vue 全局变量
		$echarts: any
	}
}
如有此问题请转到 这里

Could not find a declaration file for module ‘xxx‘
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐