【问题标题】:Vue3 Plugin Typescript TypingsVue3 插件打字稿类型
【发布时间】:2021-05-12 18:06:44
【问题描述】:

我正在尝试在 Typescript 中使用 Vue3 编写插件。但是,我从一开始就被困在如何正确键入插件函数。

这是我目前所拥有的:

import MyComponent from './src/components/my-component.vue'

import { DefineComponent, Plugin } from 'vue'

const plugin: Plugin = {
    install (app, options?: { [key: string]: any }) {
        app.mixin({
            computed: {
                classes (this: DefineComponent) {
                    // ...do things to `this`
                }
            }
        })

        app.component('MyComponent', MyComponent)
    }
}

export default plugin

最大的问题之一是如何在这些函数的上下文中处理this。目前整个屏幕都是红色的。

我正在尝试使用 rollup 进行捆绑。

这显示没有错误,但是当导入另一个 Vue 项目时它会爆炸。

如何使用 Typescript、Vue3 和 Rollup 正确键入插件函数?

【问题讨论】:

  • 使用 this 作为第一个参数是 Typescript 的事情。它让编译器知道 this 实际上是什么。

标签: typescript vuejs3 rollup


【解决方案1】:

这不是一个真正的答案,但上面的代码确实有效。

删除node_modules并重新安装后,一切正常。

我没有回答这个问题,因为我花了一段时间才找到 Plugin

import { DefineComponent, Plugin } from 'vue'

const plugin: Plugin = {
    install (app, options?) {
       app.mixin({
           computed: {
               classes (this: DefineComponent) {
                   // Do stuff here. Even with `this`
               }
           }
       })
    } 
}

使用this作为函数的第一个参数告诉Typescript编译器this实际上是什么。

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2019-05-03
    • 2022-10-14
    • 2021-07-02
    • 2021-12-24
    • 2022-01-22
    • 2021-08-05
    • 2021-07-19
    相关资源
    最近更新 更多