typescript为Vue库定义添加属性

时间:2018-01-03 11:47:28

标签: typescript vue.js

我使用包含类型的vue。但是我想使用某些插件添加的属性。

e.g。

Vue.$ga
Vue.$router

Typescript抱怨说Vue没有这些属性。我可以以某种方式将这些全局添加到Vue定义中吗?

2 个答案:

答案 0 :(得分:5)

是的,你可以:

import Vue from 'vue'

declare module 'vue/types/vue' {
    interface VueConstructor {
        $ga: any; // define real typings here if you want
        $router: any;
    }
}

您可以找到有关Vue here

的更多信息

答案 1 :(得分:2)

在main.ts上,添加:

Vue.prototype.$ga = 'your ga service'

在项目/ src文件夹中创建定义文件“ my-file.d.ts”。

import Vue, { VueConstructor } from 'vue';

declare module 'vue/types/vue' {

    interface Vue {
        $ga: any;
    }

    interface VueConstructor {
        $ga: any;
    }
}

declare module 'vue/types/options' {
    interface ComponentOptions<V extends Vue> {
        $ga?: any;
    }
}

现在,您可以通过简单的操作在组件内部使用它:

console.log(this.$ga); // your ga service