Antoine Kurka
Antoine Kurka

Reputation: 322

Error of scope in VueJS project & TypeScript

I have a an error in a VueJS project with TypeScript where my vue files are splitted in HTML, CSS, TS and vue.

I have this error : Property '$router' does not exist on type '{ validate(): void; }'

Here is how my files are splitted :

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

So with this error, I cannot build my app.

Do someone have any idea ?

Thank you !

Antoine

Upvotes: 2

Views: 1120

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

To get types inference you should create the component using Vue.extend({}) :

Login.ts

import Vue from "vue"

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

Upvotes: 6

Related Questions