简体   繁体   English

打字稿将属性添加到 Vue 库定义

[英]typescript add properties to Vue library definitions

I use vue which includes types.我使用包含类型的 vue。 However I want to use some properties that are added by certain plugins.但是我想使用某些插件添加的一些属性。

eg例如

Vue.$ga
Vue.$router

Typescript complains that Vue does not have those properties. Typescript 抱怨 Vue 没有这些属性。 Can I somehow add those globally to the Vue definition?我可以以某种方式将它们全局添加到 Vue 定义中吗?

Yes you can:是的你可以:

import Vue from 'vue'

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

You can find more info specific to Vue here您可以在此处找到特定于 Vue 的更多信息

On main.ts, add:在 main.ts 上,添加:

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

Create a definition file 'my-file.d.ts' on your project /src folder.在您的项目 /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;
    }
}

Now you can use it inside your component by simple doing:现在您可以通过简单的操作在组件中使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM