【问题标题】:How to augment the Vue class and keep typescript definition in sync如何扩充 Vue 类并保持打字稿定义同步
【发布时间】:2017-08-25 19:42:38
【问题描述】:

我正在扩展默认的 Vue 对象

export default (Vue) => {
  Object.defineProperties(Vue.prototype, {
    $http: {
      get () {
        return axiosInstance
      }
    }
  })
}

我正在使用打字稿,当然打字稿不喜欢这样。 我怎样才能创建一个项目特定的 .d.ts 文件,这样 vue typescript 声明就增加了上述扩展名?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    现在https://vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins 上有关于此的优秀文档:

    用于插件的增强类型

    插件可以添加到 Vue 的全局/实例属性和组件中 选项。在这些情况下,需要类型声明来制作插件 在 TypeScript 中编译。幸运的是,有一个 TypeScript 功能 扩充现有类型称为模块扩充。

    例如,使用类型声明实例属性 $myProperty 字符串:

    // 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 {
        $myProperty: string
      }
    }
    

    将上述代码作为声明文件包含后(如 my-property.d.ts) 在你的项目中,你可以在 Vue 上使用 $myProperty 实例。

    var vm = new Vue()
    console.log(vm.$myProperty) // This should compile successfully
    

    您还可以声明额外的全局属性和组件 选项:

    import Vue from 'vue'
    
    declare module 'vue/types/vue' {
      // Global properties can be declared
      // on the `VueConstructor` interface
      interface VueConstructor {
        $myGlobal: string
      }
    }
    
    // ComponentOptions is declared in types/options.d.ts
    declare module 'vue/types/options' {
      interface ComponentOptions<V extends Vue> {
        myOption?: string
      }
    }
    

    以上声明允许编译以下代码:

    // Global property
    console.log(Vue.$myGlobal)
    
    // Additional component option
    var vm = new Vue({
      myOption: 'Hello'
    })
    

    【讨论】:

      【解决方案2】:

      创建一个包含以下内容的文件:

      import {AxiosStatic} from 'axios';
      
      
      declare module 'vue/types/vue' {
        export interface Vue   {
          $http: AxiosStatic;
        }
      }
      

      【讨论】:

      • 文件名是什么,需要放在哪里??? :-(
      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      相关资源
      最近更新 更多