【问题标题】:Error of scope in VueJS project & TypeScriptVueJS 项目和 TypeScript 中的范围错误
【发布时间】:2021-04-29 03:06:16
【问题描述】:

我在一个带有 TypeScript 的 VueJS 项目中出现错误,我的 vue 文件被拆分为 HTML、CSS、TS 和 vue。

我有这个错误:属性 '$router' 在类型 '{ validate(): void; 上不存在}'

这是我的文件的拆分方式:

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

因此出现此错误,我无法构建我的应用程序。

有人知道吗?

谢谢!

安东尼

【问题讨论】:

    标签: typescript vue.js vue-router


    【解决方案1】:

    要获得类型推断,您应该使用 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')
                }
            }
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-16
      • 2020-05-06
      • 2020-04-26
      • 2017-04-02
      • 2021-08-03
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      相关资源
      最近更新 更多