首页 > 解决方案 > 如何为 vue 插件添加类型?

问题描述

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

但是当我使用 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 })
        })
    }
}

myPlugin.d.ts

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

零件

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)
        }
    }


}

标签: typescriptvue.jsvuejs2

解决方案


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

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

TS Docs(参见模块扩充部分): 声明合并


更新

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

Vue 文档: 用于插件的增强类型


推荐阅读