如何扩充 Vue 类并使打字稿定义保持同步 [英] How to augment the Vue class and keep typescript definition in sync

查看:25
本文介绍了如何扩充 Vue 类并使打字稿定义保持同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在扩展默认的 Vue 对象

I'm extending the default Vue object with

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

我正在使用打字稿,当然打字稿不喜欢这样.我怎样才能创建一个特定于项目的 .d.ts 文件,这样 vue 打字稿声明就可以用上述扩展名进行扩充?

I'm using typescript and of course typescript doesn't like this. How can i create a project specific .d.ts file in such a way the vue typescript declaration is augmented with the above extension?

推荐答案

现在在 https://vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins:

用于插件的扩充类型

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

Plugins may add to Vue’s global/instance properties and component options. In these cases, type declarations are needed to make plugins compile in TypeScript. Fortunately, there’s a TypeScript feature to augment existing types called module augmentation.

例如,声明一个类型为 $myProperty 的实例属性字符串:

For example, to declare an instance property $myProperty with type string:

// 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实例.

After including the above code as a declaration file (like my-property.d.ts) in your project, you can use $myProperty on a Vue instance.

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

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

You can also declare additional global properties and component options:

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
  }
}

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

The above declarations allow the following code to be compiled:

// Global property
console.log(Vue.$myGlobal)

// Additional component option
var vm = new Vue({
  myOption: 'Hello'
})

这篇关于如何扩充 Vue 类并使打字稿定义保持同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆