【问题标题】:Augmenting Types for Use with Plugins for Vue 3用于 Vue 3 插件的增强类型
【发布时间】:2026-02-03 00:15:01
【问题描述】:

起初:我知道有一个类似的问题 (Question about Vue 3 + TypeScript and Augmenting-Types-for-Use-with-Plugins),但它被错误地关闭了。

对于 Vue 2,文档中有一个关于将插件与 typescript 一起使用的条目:Augmenting Types for Use with Plugins,但对于 Vue 3 则没有。

总结一下,我想要实现的目标:我想在组件defineComponent() 中使用我的插件作为this.$my-plugin(),但是当我按照Vue 2 的指南操作时,我收到了错误Property '$my-plugin' does not exist on type 'ComponentPublicInstance[...]。所以我假设必须更改 .d.ts 文件的语法。我当前的文件:

import { Vue } from 'vue';

import MyPlugin from './my-plugin';

declare module 'vue/types/vue' {
    interface Vue {
        $my-plugin: MyPlugin
    }
}

【问题讨论】:

    标签: typescript vue.js vuejs3


    【解决方案1】:

    main.ts 中添加ComponentCustomProperties'@vue/runtime-core' 模块:

    import { createApp } from 'vue'
    import App from './App.vue'
    import MyPlugin from './my-plugin';
    ...
    
    declare module '@vue/runtime-core' {
      interface ComponentCustomProperties  {
         $myPlugin: MyPlugin //don't use kebab-case as key in js
         }
       }
    let app=createApp(App)
    app.config.globalProperties.$myPlugin= MyPlugin ;
    
    app.mount('#app')
    
    

    【讨论】: