簡體   English   中英

如何為 vue 聲明一個 JS mixin?

[英]How to declare a JS mixin for vue?

我正在用 typescript 編寫一個 vue 項目,我想使用由 javascript 編寫的 thrid-part 庫中的 mixin,如何編寫.d.ts以使 ts 可以在 mixin 中找到函數定義?

我試過這種方式,但它不起作用:

// common.d.ts
declare module 'thrid-part-lib' {
    import { VueClass } from 'vue-class-component/lib/declarations';

    export interface SomeMixin<T> extends VueClass<T> {
        refresh(): Promise<void>;
    }
}
// index.ts
import { Component, Mixins } from 'vue-property-decorator';
import { SomeMixin } from 'thrid-part-lib';

@Component
export default class Index extends Mixins(SomeMixin) {
    public foo() {
        this.refresh(); // 'refresh' is not define.
    }
}

您可以通過創建類似vuelidate-error-extractor.d.ts的文件來擴充第三方 mixin:

declare module 'vuelidate-error-extractor' {
   import { ValidationRule } from 'vuelidate/lib/validators';

   // eslint-disable-next-line @typescript-eslint/class-name-casing
   export class singleErrorExtractorMixin extends Vue {
      readonly events: any;

      readonly name: string;

      readonly isValid: boolean;

      readonly hasErrors: boolean;

      readonly preferredValidator: ValidationRule;
   }
}

這增加了這個 JS 文件,但是以不完整的方式。

這在“Augmenting Types for Use with Plugins”中有記錄。

將其放在項目中的.d.ts文件中,以向組件添加refresh()混合方法:

// 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 {
    refresh():  void;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM