vue2+ts:往Vue的原型对象上绑定自定义的全局属性,xxx.vue页面使用报错:Property ‘$C‘ does not exist on type ‘AvailableStock‘.
添加自定义类型声明文件xx.d.ts并在tsconfig.json中配置即可。
·
官网文档解释:TypeScript Support — Vue.js
一、在main.ts中往Vue的原型对象上绑定自定义全局属性,如:$C
// main.ts
import constVariable from '@/utils/const'
Vue.prototype.$C = constVariable
二、在src/types目录中,新建自定义.d.ts类型文件如:my-property.d.ts
// 1. Make sure to import 'vue' before declaring augmented types
import Vue from 'vue'
// 2. Specify a file with the types you want to augment
// Vue has the constructor type in types/vue.d.ts
declare module 'vue/types/vue' {
// 3. Declare augmentation for Vue
interface Vue {
$C: any
}
}
三、修改项目根目录下的 tsconfig.json 文件,将types目录添加到include属性即可
配置include属性字段:让自定义的xx.d.ts类型文件全局生效。
注意:配置后,如果编辑器仍显示类型报错,记得关闭并重启下vscode即可!
{
"compilerOptions": {
... // 省略code
"paths": {
"@/*": [
"src/*"
]
}
},
"include": [
"types",
"src/**/*.d.ts",
"src/**/*.ts",
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
参考网址:
- typescript - How to include .d.ts file manually(locally)? Or How to use a user defined .d.ts file? - Stack Overflow
- vue.js - VueJS + Typescript: Property does not exist on type - Stack Overflow
其他old解决方法:
3步处理。
步骤1:在main.ts中给Vue的原型对象绑定全局属性。
// main.ts
import constVariable from '@/utils/const'
Vue.prototype.$C = constVariable
步骤2:在src文件下新建vue.d.ts(用于:让ts识别.vue文件,声明第三方库等)
// vue.d.ts 处理: 让ts识别.vue 文件
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
declare module 'element-ui/lib/locale/lang/*' {
export const elementLocale: any
}
declare module '*.gif' {
export const gif: any
}
declare module '*.svg';
declare module '*.png';
declare module '*.jpg';
declare module '*.jpeg';
declare module '*.bmp';
declare module '*.tiff';
declare module '_';
// TODO: remove this part after vue-count-to has its typescript file
declare module 'vue-count-to' // 第三方库
// TODO: remove this part after vue2-dropzone has its typescript file
// TODO: remove this part after vue-image-crop-upload has its typescript file
declare module 'vue-image-crop-upload'
declare module 'alife-logger'
步骤3:在src文件下新建shims.d.ts(用于:新增全局属性的处理)
import Vue from 'vue'
import { Store } from 'vuex'
declare module 'vue/types/vue' {
interface Vue {
$store: Store,
$axios: any, // 挂载的vue全局属性
$echarts: any
$C: any // 挂载的全局常量
}
}
参考链接:【已解决】TS. Property ‘$axios‘ does not exist on type ‘xxx‘;_bao-CSDN博客
更多推荐
已为社区贡献16条内容
所有评论(0)