2

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

1 Answer 1

6

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')
            }
        }
    }
})
Sign up to request clarification or add additional context in comments.

1 Comment

Also, we can use defineComponent instead of Vue.extend if we're using Vue 3. I had the same problem and it helped me

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.