我正在尝试在 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 正确键入插件函数?
答案 0 :(得分:0)
这不是真正的答案,但上面的代码确实有效。
删除 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
实际上是什么。