16

I try add self plugin for vue with type script.

But at moment when i use my method from vue prototype, my method $auth does not exist on type myComponent. I also add .d.ts for plugin, but i think he is little not correct, and also i think in plugin don't need use install, or need? Just in some examples i dont see install, but in docs say - need use install.

my plugin

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

component

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


}

1 Answer 1

7
  1. install function is a strict requirement, this function is used by Vue internally in Vue.use(YourAwesomePlugin) to load your plugin.

  2. I could not make the declaration file work as well as you mentioned, but in docs examples an author put the declaration merging in a file with logic (not in a separate d.ts). So if you put content of your myPlugin.d.ts to a main plugin file - it will load your interface and $auth will exist on this.

TS Docs(see Module Augmentation section): Declaration Merging


UPDATE

To make .d.ts file work you just need to import vue in that file.

Vue docs: Augmenting Types for Use with Plugins

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.