【问题标题】:Vue augmented types - XYZ does not exist on typeVue 增强类型 - 类型上不存在 XYZ
【发布时间】:2019-02-18 00:33:59
【问题描述】:

我正在使用带有 typescript 的 vue 类组件,我需要扩充类型以使用第三方模块。

组件

export default class TestComponent extends Vue  {

   private created() {
     this.$snotify.success('test')
   }
}

shims.d.ts

import Vue from 'vue'
import { Snotify } from 'vue-snotify'

declare module 'vue/types/vue' {
    interface VueConstructor {
      $snotify: Snotify
    }
  }

“TestComponent 类型上不存在属性 $snotify”

Vue.$snotify 存在,但 this.$snotify 不存在,即使 this 扩展了 Vue

我哪里错了?

【问题讨论】:

    标签: typescript vue.js vuejs2 vue-component


    【解决方案1】:

    尝试增加Vue 类型而不是VueConstructor

    declare module 'vue/types/vue' {
      interface Vue {
        $snotify: Snotify
      }
    }
    

    【讨论】:

      【解决方案2】:

      接受的答案似乎并不实际,请查看@RomainLanz 在a related vue-snotify GitHub issue 上的答案:

      import Vue from 'vue'
      import { SnotifyService } from 'vue-snotify/SnotifyService'
      
      declare module 'vue/types/vue' {
        interface Vue {
          $snotify: SnotifyService
        }
      }
      

      在此处添加此答案,因为这是搜索相同内容时出现的页面之一。

      【讨论】:

      • 虽然交叉引用相关的权威线程肯定很有用,但这与几年前@Decade-Moon 提供的解决方案不一样吗?
      • 不是。主要是因为不完全清楚要导入什么,并且类型本身在尝试编译时会抛出 ts 错误。它特别是 { SnotifyService } 应该用作类型,以便它按照文档指示的那样工作。
      • 啊哈!这是一个有用的点。谢谢你。您介意更新您的答案以包含它吗?区分相似的答案有助于用户浏览主题以快速找到合适的解决方案。
      猜你喜欢
      • 2021-03-26
      • 2015-12-28
      • 2020-12-18
      • 2021-12-17
      • 2019-02-14
      • 1970-01-01
      • 2022-01-07
      • 2020-12-11
      • 2023-01-03
      相关资源
      最近更新 更多