如何为 vue 插件添加类型?

Dro*_*rop 12 typescript vue.js vuejs2

我尝试使用类型脚本为 vue 添加 self 插件。

但是当我使用 vue 原型中的方法时,我的方法$auth在 myComponent 类型上不存在。我还为插件添加了.d.ts,但我认为他有点不正确,而且我认为插件不需要使用安装,还是需要?只是在一些例子中我没有看到安装,但在文档中说 - 需要使用安装。

我的插件

import _Vue from 'vue';
import store from '@/store'
import * as firebase from 'firebase';

export default {
    install: (Vue: typeof _Vue, options?: any) => {
        const base = firebase.initializeApp(config);
        const auth = firebase.auth();
        Vue.prototype.$auth = {
            login: async (username: string, pass: string) => {
                return await auth.signInWithEmailAndPassword(username, pass)
            },
            logout: async () => {
                await auth.signOut()
            }
        };
        auth.onAuthStateChanged((user: any) => {
            store.commit('updateUser',{ user })
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

myPlugin.d.ts

declare module 'vue/types/vue' {
    interface Vue {
        $auth: {
            login: (username: string, pass: string) => Promise<any>
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

成分

export default class SignUp extends Vue {
    email: string = '';
    password: string = '';

    async onSubmit(){
        if ((this.$refs.form as any).validate()) {
            const auth = await this.$auth.login(this.email, this.password)
        }
    }


}
Run Code Online (Sandbox Code Playgroud)

Max*_*nev 6

  1. install函数是一个严格的要求,这个函数被 Vue 内部Vue.use(YourAwesomePlugin)用来加载你的插件。

  2. 我无法使声明文件像你提到的那样工作,但在文档示例中,作者将声明合并到一个带有逻辑的文件中(而不是单独的d.ts)。因此,如果您将您的内容放入myPlugin.d.ts主插件文件 - 它会加载您的界面$auth并存在于this.

TS Docs(参见模块增强部分): 声明合并


更新

要使.d.ts文件工作,您只需要在该文件中导入 vue。

Vue 文档:增加 插件使用的类型