Scope Error in VueJS Project with TypeScript

I'm facing an issue in my VueJS project with TypeScript where my vue files are divided into HTML, CSS, TS, and vue.

The error message I'm getting is: Property '$router' does not exist on type '{ validate(): void; }'

Here is the breakdown of how my files are organized:

Login.vue :

<template src="./Login.html"></template>
<script src="./Login.ts"></script>
<style src="./Login.css"></style>

Login.html :

<div id="form" align="center" justify="center">

  <v-col sm="4" align="center" justify="center">
    <v-form ref="form" v-model="valid" lazy-validation>
      <v-text-field v-model="login" :label="$t('Username')" required></v-text-field>

      <v-text-field v-model="password" :label="$t('Password')" type="password" required></v-text-field>

      <v-btn color=primary class="mr-4" @click="validate">
        {{ $t('Login') }}
      </v-btn>

    </v-form>
  </v-col>
</div>

Login.ts :

export default {
    name: 'Login',
    data() {
        return {
            fields: {
                login: '',
                password: ''
            }
        }
    },
    methods: {
        validate() {
            if ("admin" === this.login && "admin" === this.password) {
                this.$router.push('index')
            }
        }
    }
}

Due to this error, I'm unable to successfully compile my app. Any suggestions or ideas would be greatly appreciated!

Thank you,

Antoine

Answer №1

To achieve type inference, you can create the component using Vue.extend({}):

LoginComponent.ts

import Vue from "vue"

export default Vue.extend({
    name: 'Login',
    data() {
        return {
            fields: {
                username: '',
                password: ''
            }
        }
    },
    methods: {
        validateUser() {
            if ("admin" === this.fields.username && "admin" === this.fields.password) {
                this.$router.push('dashboard')
            }
        }
    }
})

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

What is the best way to ensure that all components are updated simultaneously?

I am facing an issue with showcasing relative time using momentjs - it displays 'a few seconds ago', '5 minutes ago', 'an hour ago', etc... upon rendering the HTML. However, the problem is that it remains stuck in that initial ...

The imagemin code runs successfully, however, there appears to be no noticeable impact

I've been attempting to compress an image in Node 14 using Typescript and the imagemin library. After following some online examples, I executed the code but it seems that nothing is happening as there are no errors reported upon completion. The outp ...

The deployed vue.js application encounters a 404 error when the page is refreshed within the vue-router

While the homepage/base URL of the app can be refreshed with no problem, other pages return a 404 error when refreshed. Are there any workarounds for this issue? Take a look at this screenshot of the 404 error: [1]: https://i.sstatic.net/lc8xD.png ...

CSS: Problem Arising from Line Connections Between Tree Elements

I'm currently working on connecting tree nodes with lines in a drawing. I've managed to achieve it to some extent, but there are a few issues like dangling lines that I need to fix. You can find the implementation on codepen here: https://codepe ...

Retrieve an array object containing specific properties using axios

Currently, I am retrieving JSON data from an API call using axios and displaying it through Vue. This snippet shows the JSON Object logged in the console: 0: category_id: "categ1" item_name: "item1" price: 100 stock: 155 1: c ...

Utilizing Angular CDK to link several drop zones together using the cdkDropListConnectedTo directive

Currently in the process of designing a basic board interface with swim lanes similar to Jira swimlane or trello boards https://i.sstatic.net/7MBvm.png The red lines indicate the current flow The blue lines represent the flow that I aim to implement The ...

What methods can be used to prevent an input event from occurring if the validation process is

I have a straightforward input field that only accepts integers. However, when I use e.preventDefault() and return to stop the input event, the input event continues working. input v-on:input="changeFraction" name="denominator" type="text" ...

Error in Angular 4: Undefined property 'replace' causing trouble

I've been trying to use the .replace() JavaScript function in Angular 4 to remove certain characters from a string. Here is the code snippet from my component: @Component({...}) export class SomeComponent implements OnInit { routerUrl: string = &apo ...

The Process of Developing Vue Micro UI/Web Components

Looking for ways to enhance my team's local development workflow... We have a Vue CLI shell application project that runs locally using node. Additionally, we have several small Vue CLI web-component applications served up via node. When the shell i ...

Creating a sleek and modern web application using Laravel 5 and Vue JS

Using Vue JS in my Laravel 5 application is causing a blank page to appear when I use v- new Vue({ el: '#vApp', data: { todos: [ { text: 'Learn JavaScri ...

Namespace modifications did not successfully compile in Typescript

I am facing an issue with extending the User type in express.js by including an express.d.ts declaration file in my project. Although adding the declaration file removes the error indicators in VS Code, Typescript is failing to compile. I am encountering e ...

When converting to a React Functional Component using Typescript, an error occurred: The property 'forceUpdateHandler' could not be found on the type 'MutableRefObject<Spinner | null>'

Looking to convert the App component in this CodePen into a Functional component using Typescript. Encountering an error when attempting to run it: ERROR in src/App.tsx:13:14 TS2339: Property 'forceUpdateHandler' does not exist on type 'Mu ...

Experiencing strange sorting issues with @dnd-kit when moving a draggable element that contains multiple items from the list

Encountering a problem while using dnd-kit! When I switch the draggable with the first element from the list (either above or below), it works smoothly. However, continuing to drag and swap with the subsequent elements leads to unusual sorting behavior. H ...

Setting up a Webpack configuration for packaging a Vue component as an npm module

Below is the primary JavaScript code for my component: import './sass/main.scss' import Vlider from './Vlider.vue' function install(Vue) { if (install.installed) return; install.installed = true; Vue.component('vlider ...

The issue of recursive updates is triggered by reactive props within Vue3 Treelist

I am currently utilizing vue3-tree for my project and I am attempting to set up the nodes. I am using pinia to store props.filter.data up to the parent component, but I am encountering this error: Uncaught (in promise) Maximum recursive updates exceeded. ...

Troubleshooting Generic Problems in Fastify with TypeScript

I am currently in the process of creating a REST API using Fastify, and I have encountered a TypeScript error that is causing some trouble: An incompatible type error has occurred while trying to add a handler for the 'generateQrCode' route. The ...

A guide on combining two counters in Vue to create a unified value

Is there a way to track the number of times two buttons are clicked individually as well as together? <div id="app"> <p><button v-on:click="counter1 += 1">Add One More Click</button></p> <p>&l ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

The Server Discovery And Monitoring engine has been marked as obsolete

Currently, I am integrating Mongoose into my Node.js application with the following configuration: mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }).then ...

What are the steps to use the vue-text-highlight feature?

I am attempting to implement an example from the basic usage section of https://github.com/AlbertLucianto/vue-text-highlight. However, upon opening index.html in Firefox, I am only greeted with a blank page. You can find the code I am using at https://git ...