【已解决】TS. Property ‘$axios‘ does not exist on type ‘xxx‘;
问题在 vue 中使用 typescript. 在 mian.ts vue 原型绑定属性 Vue.prototype.$axios = axios, 在组件中使用的时候编辑器报错, 但是可以正常运行代码.解决办法方法1:指定 this 类型为 any, 但是使用 any 就失去了类型安全保障, 又得不到工具的支持, 写起来也不太雅观.方法2:在组件内申明 $axios: any, 这样每个组件内都
文章目录
问题
在 vue 中使用 typescript. 在 mian.ts vue 原型绑定属性 Vue.prototype.$axios = axios, 在组件中使用的时候编辑器报错, 但是可以正常运行代码.
解决办法
方法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
文件.
解决办法
这个解决办法 就. 就…
![](https://img-blog.csdnimg.cn/20210301145639869.png)
就是 shims.d.ts
中不要在 块
的外部引入使用 import
.
在块外部引入, 又不能解决 ts
找不到原型属性问题.
方法4: 完美解决
我刚才又试了一下新的方法. 完美解决这个问题 🙄
把方法 3
方法3 的代码写在 main.ts
中即可. 因为 main.ts
中默认引入了vue 就不用再次引入.
方法5: 完美解决以上两个问题.
2021-03-02 … 更
- 把
shims-vue.d.ts
拆分为两个文件. - 在
shimis-vue.d.ts
同级目录新建vue.d.ts
<名字随意, 我是这样定义的>, 代码:
// vue.d.ts 处理 识别 .vue 文件
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
- 修改
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‘
更多推荐
所有评论(0)