我用
扩展默认的Vue对象export default (Vue) => {
Object.defineProperties(Vue.prototype, {
$http: {
get () {
return axiosInstance
}
}
})
}
我使用打字稿,当然打字稿并不是这样的。 如何以这样的方式创建项目特定的.d.ts文件,使用上面的扩展名增加了vue typescript声明?
答案 0 :(得分:6)
创建包含以下内容的文件:
import {AxiosStatic} from 'axios';
declare module 'vue/types/vue' {
export interface Vue {
$http: AxiosStatic;
}
}
答案 1 :(得分:5)
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' })