【问题标题】:typescript add properties to Vue library definitions打字稿将属性添加到 Vue 库定义
【发布时间】:2018-06-13 02:12:25
【问题描述】:

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

例如

Vue.$ga
Vue.$router

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

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    是的,你可以:

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

    您可以找到更多特定于 Vue 的信息 here

    【讨论】:

      【解决方案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
      

      【讨论】:

        猜你喜欢
        • 2017-11-14
        • 1970-01-01
        • 2023-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多