ts 扩展功能到Vue原型(this)上

使用 typescript + Vue 开发,经常会导入一些功能到Vue原型上,比如通过 Vue.prototypeVue.use()Vue.mixin() 等方法把想要功能添加到 原型上,添加成功了也能用,但是使用this访问说找不到。

报错:

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 文件(如果文件已存在可以继续添加代码,在src下 新建一个)。
2、用 ts 的 declare module 语法把类型导入到Vue的实例里。语法请查看 ts 文档

Vue3 在 type.d.ts 文件添加以下内容

官方文档

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 文件添加一下内容

官方文档

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。