使用 typescript + Vue 開(kāi)發(fā),經(jīng)常會(huì)導(dǎo)入一些功能到Vue原型上刺啦,比如通過(guò) Vue.prototype
、Vue.use()
、Vue.mixin()
等方法把想要功能添加到 原型上哮针,添加成功了也能用,但是使用this訪問(wèn)說(shuō)找不到。
報(bào)錯(cuò):
Vue3: Property 'XXX' does not exist on type 'ComponentPublicInstance<{}, {}, {}, {}, {}, EmitsOptions, {}, {}, false, ComponentOptionsBase<{}, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, string, {}>>'
Vue2: Property 'XXX' does not exist on type 'CombinedVueInstance<Vue, unknown, { ontest(): Promise<void>; }, unknown, Readonly<Record<never, any>>>
解決:
1十厢、在 src 下新建 type.d.ts 文件(如果文件已存在可以繼續(xù)添加代碼等太,在src下 新建一個(gè))。
2蛮放、用 ts 的 declare module
語(yǔ)法把類型導(dǎo)入到Vue的實(shí)例里澈驼。語(yǔ)法請(qǐng)查看 ts 文檔
Vue3 在 type.d.ts 文件添加以下內(nèi)容
export {}; /// 這句不能刪
declare module 'vue' {
class C {}
interface ComponentCustomProperties {
a: C;
aa: Function;
aaa: {
aa: 'a' | 'b';
};
aaaaa: number | string | boolean | Function;
}
}
image.png
Vue2 在 type.d.ts 文件添加一下內(nèi)容
export {} /// 這句不能刪
declare module 'vue/types/vue' {
class C {}
interface Vue {
a: C
aa: Function
aaa: {
aa: 'a' | 'b'
}
aaaaa: number | string | boolean | Function
}
}
Vue.extend 模式
image.png
vue-property-decorator 模式下
image.png