【问题标题】:Vue typescript pluginVue 打字稿插件
【发布时间】:2020-03-06 22:52:58
【问题描述】:

我正在写一个 vue 记录器插件

export default new (class NestLogger {
  public install(Vue: any) {
    Vue.prototype.$log = this;
  }

  error(text: string) {
      console.log(text)
  }
})();

在 main.ts 中

import logger from "./plugins/logger";
Vue.use(logger);

但在组件中我无法引用 this.$log - 为什么?

在 Login.vue 中

this.$log.error("bla"); 

错误:Property $log does not exist on type Login

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    您需要在.d.ts 文件中添加augment the vue type definitions 以包含$log 的类型定义:

    // src/my-log-plugin.d.ts
    import Vue from 'vue'
    
    declare module 'vue/types/vue' {
      interface Vue {
        $log: {
          error: (message: string) => void
        }
      }
    }
    
    export {}
    

    【讨论】:

    • 是的,该解决方案是正确的,但是对我有用的是将上述代码包含在我的 log.ts 文件中,而不是将其拆分为 .d.ts 文件。和这个人一样stackoverflow.com/a/54656902/8518207
    • 如果添加.d.ts 文件,请确保它位于tsconfig.json 中配置的源路径中,以便tsc(和Intellisense)找到它。将其放入 src/ 适用于 Vue CLI 项目。
    猜你喜欢
    • 2018-03-11
    • 2018-01-21
    • 2021-05-12
    • 2018-12-07
    • 1970-01-01
    • 2013-11-28
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多