美文网首页
ts 扩展功能到Vue原型(this)上

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

作者: space77 | 来源:发表于2021-01-27 18:12 被阅读0次

使用 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/runtime-core' {
  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

相关文章

网友评论

      本文标题:ts 扩展功能到Vue原型(this)上

      本文链接:https://www.haomeiwen.com/subject/ttbazktx.html