首页 > 解决方案 > Vue3 Plugin Typescript Typings

问题描述

I'm trying to write a plugin with Vue3 in Typescript. However, I'm stuck from the start with how to properly type the plugin function.

This is what I have so far:

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

One of the biggest problems is how to deal with this in the context of these functions. There's just red all over the screen at the moment.

I'm trying to use rollup for bundling.

This shows no errors, but when imported into another Vue project it blows up.

How to properly type a plugin function using Typescript, Vue3 and Rollup?

标签: typescriptvuejs3rollup

解决方案


This is not really an answer, but the above code does actually work.

After deleting node_modules and reinstalling, everything worked.

I'm leaving this question up because it took a while to find Plugin.

import { DefineComponent, Plugin } from 'vue'

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

Using this as the first argument of a function tells the Typescript compiler what this actually is.


推荐阅读