Exploring the process of incorporating types for a Vue plugin

I am currently trying to integrate a self-made plugin for Vue with TypeScript.

However, when I try to use the method from my vue prototype, I encounter an issue where my method $auth is not recognized on type 'myComponent'. I have also included a .d.ts file for the plugin, but I suspect there may be some issues with it. Additionally, I am unsure if the install function is required in the plugin. While some examples do not include it, the documentation states that it is necessary.

My Custom 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 Definition

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

Answer №1

  1. Installing a function is essential, as Vue internally uses this function in Vue.use(YourAwesomePlugin) to load your plugin.

  2. I did not find success in making the declaration file work as described. However, in the documentation examples, an author incorporated declaration merging within a file containing logic (not in a separate d.ts file). So, by placing the content of your myPlugin.d.ts into the main plugin file, it will bring your interface and ensure that $auth exists on this.

Check out the TypeScript Docs (refer to the Module Augmentation section): Declaration Merging


UPDATE

To enable the .d.ts file to work, simply import Vue into that file.

For further information, visit the Vue docs: Augmenting Types for Use with Plugins

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with xml2js within the Quasar framework version 2.6.0

To integrate the following code into a Quasar 2.6.0 application, I am encountering an issue that needs attention. async fetchAbstracts() { try { const url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=33888705,183 ...

Discover the ways to reach the router in Nuxt outside of the Vue component scope

When working with Nuxt.js, I have a helper function that needs to be able to navigate the router programmatically. In Vue.js, I would typically achieve this by importing the router using `import router from "@/router"`. However, how can I accomplish this m ...

Tips for updating a boolean value in a JSON file with a button in Angular and TypeScript

Can someone guide me on how to create a function in my table-viewer.component.ts file that can update the status from "false" to "true" in a JSON file when a user clicks the cancel button? The JSON file has the following information. db.json "firstN ...

Is it possible to invoke a Vue method during the rendering process?

Everything is performing as anticipated. This indicates that during the rendering process, the JSON data effectively converts to a CSV string as the attribute value. JSON: "functions": { "function": [ { "name": "foo" }, ...

Begin the Desktop PWA in immersive full-screen or kiosk mode

I've been on the lookout for a solution, but nothing seems to do the trick. My goal is to launch a PWA from a Windows Desktop computer using Chrome in kiosk mode or at the very least, full-screen (without any menu bars). I would have expected this to ...

Setting up a Contact Email for your Nuxt Static Generated site: A Step-by-Step Guide

I have a website built on Nuxt and hosted on Netlify. I utilized the 'static' method in my nuxt.config.js file to generate the dist folder. My goal is to trigger an email notification whenever a user submits a contact form on my site. It functio ...

The PasswordResetView in Django using Vue.js encounters a 403 Forbidden error when attempting to post with Axios due to an

I'm currently working on building a unique Email Restore page in the frontend using Vue.js. My goal is to send email input data via Axios to /api/v1/accounts/password_reset/, essentially utilizing the original ResetPasswordView as an endpoint instead ...

The Vue website on S3 is experiencing a 404 error, but it is still able to

I'm facing an issue with my Vue2 site where everything seems to be working fine for the users, but Google is flagging most of the pages as having 404 errors. Even though when accessing a direct URL like hptts://example.com/example, the page loads corr ...

Differentiating Typescript will discard attributes that do not adhere to an Interface

Currently, I am working with an API controller that requires a body parameter as shown below: insertUser(@Body() user: IUser) {} The problem I'm facing is that I can submit an object that includes additional properties not specified in the IUser int ...

Filter an object in Typescript and retrieve a single key

Managing a set of checkboxes is essential in assigning roles to new users. While it's possible to filter and retrieve only the checked checkboxes, extracting just the "name" key poses a challenge. The current method involves filtering with a for loop ...

Having trouble implementing a multi-level sub menu in a popup menu in Vue.js?

data: { menuItems: [{ name: 'Item 1', children: [{ name: 'Subitem 1' }, { name: 'Subitem 2' }, { name: 'Subitem 3' }] }, { ...

Implementing bidirectional data binding with Semantic UI's search dropdown feature in Vue.js

I'm currently facing an issue with the Semantic-UI searchable dropdown and Vuejs data binding. It seems like only one changed option is being model-bound, no matter which dropdown option I select. Here's a snippet of my code. I attempted to use ...

utilizing varying environments for specific scenarios within a nuxt application

I am new to Nuxt or any type of node technology. I am attempting to create different environments for various scenarios. For example, if I want to test my app, I would like the dev object block to run (pointing to a dev endpoint). Here is an example: [ p ...

Is it possible to conditionally redirect using Vue router?

I am in the process of creating a straightforward Vue application where the router links will be determined by the data retrieved from the server. The format of the data looks something like this: id: 1 path: "category_image/About.jpg" slug: &quo ...

Storing arrays of objects in Laravel involves creating models, defining relationships between them,

I am in a situation where I have a form set up with specific input fields for shipping rules. The form structure is as follows: <shipping-rules-form> <div class="row" v-for="(input,index) in form.inputs" :key="index&qu ...

The Server Components render encountered a glitch

Screenshot of the errorI am encountering a strange error only in the production environment. The lack of additional information leads me to believe it may be due to security measures put in place for production. Unfortunately, I have been unable to repli ...

specifying a specific type in a declaration

In this scenario, my goal is to distinguish between different types when declaring a new type: type Schedule = { flag_active : boolean, } type Channel = { flag_archived : boolean } type CreateChangeLog = { from : null, to : Schedule | Channel } ty ...

Is it possible to effortlessly associate a personalized string with an identifier within an HTML element utilizing Angular2?

Check out this cool plunker import {Component} from 'angular2/core' @Component({ selector: 'my-app', template: ` <div *ngFor="#option of myHashMap"> <input type="radio" name="myRadio" id="{{generateId(option[& ...

Attempting to authenticate with Next.js using JWT in a middleware is proving to be unsuccessful

Currently, I am authenticating the user in each API call. To streamline this process and authenticate the user only once, I decided to implement a middleware. I created a file named _middleware.ts within the /pages/api directory and followed the same appr ...

Is it possible for me to determine when all images have finished loading in order to update the isLoaded variable to true?

I am using the template below: <template> <div v-if='isLoaded'> <div @click='selectSight(index)' v-for='(sight, index) in sights'> <img :src="'https://maps.googleapis.com/maps ...