【问题标题】:how to add types for vue plugin?如何为 vue 插件添加类型?
【发布时间】:2019-08-14 03:32:22
【问题描述】:

我尝试使用类型脚本为 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 })
        })
    }
}

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


}

【问题讨论】:

    标签: typescript vue.js vuejs2


    【解决方案1】:
    1. install函数是一个严格的要求,这个函数是Vue内部在Vue.use(YourAwesomePlugin)中用来加载你的插件的。

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

    TS 文档(参见模块增强部分): Declaration Merging


    更新

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

    Vue 文档: Augmenting Types for Use with Plugins

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 2018-08-17
      • 2011-10-10
      • 2019-10-21
      • 2019-07-09
      • 2021-07-03
      • 2021-02-20
      • 1970-01-01
      • 2019-12-05
      相关资源
      最近更新 更多