【问题标题】:Getting this error: Cannot read property 'length' of undefined收到此错误:无法读取未定义的属性“长度”
【发布时间】:2021-06-02 19:26:55
【问题描述】:

我正在使用 nuxt 构建一个应用程序(使用 vuetify 2 和 typescript)。

我有单选按钮(比如 b1 b2)和文本字段(比如 t1 t2 t3)。

当用户点击 b1 时,显示 t1 和 t3

当用户点击b2时,显示t2和t3

我认为字段 t1 的验证导致错误,但不确定原因。

用户打开页面时,默认选择b1。

当我切换到 b2 并写一些东西......然后回到 b1 时,什么都没有发生。它可以按需要工作。

当我切换到 b2 然后切换回 b1 而不写任何内容时,我收到 Cannot read property 'length' of undefined 错误。

我首先认为我收到此错误是因为id 未定义但id 的默认值是'test',并且在我切换回b1 时testdata 已经初始化所以我很困惑......

这是我的简化代码:

<template>
  <v-app>
    <v-container justify="center">
      <v-card flat width="400" class="mx-auto mt-5 mb-6">
        <v-card-text>
          <v-form v-model="isFormValid" class="pa-3">
            <v-radio-group v-model="testdata.type" row>
              <v-radio label="b1" value="b1"></v-radio>
              <v-radio label="b2" value="b2"></v-radio>
            </v-radio-group>
            <v-text-field v-if="testdata.type == 'b1'" v-model="testdata.id" counter :rules="[rules.required, rules.id]" />
            <v-text-field v-if="testdata.type == 'b2'" v-model="testdata.id2" :rules="[rules.required]" />
            <v-text-field v-model.number="testdata.price" type="number" :rules="[rules.required]"/>
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" @click="somemethod()" :disabled="isLoading || !isFormValid" :loading="isLoading">submit</v-btn>
          <v-spacer></v-spacer>
        </v-card-actions>
      </v-card>
    </v-container>
  </v-app>
</template>
<script lang="ts">
import Vue from 'vue';

interface SomeDto {
 type: 'b1'|'b2'; id:string; id2:string; price:number
}

interface Data {
  rules: any;
  isFormValid: boolean;
  testdata: SomeDto;
  isLoading: boolean;
}
export default Vue.extend({
  data(): Data {
    return {
      isFormValid: false,
      isLoading: false,
      testdata: {type: 'b1', 'id:'test', id2:'', price:0},
      rules: {
        required: (value: any) => !!value || 'required',
        id: (value: string) => value.length == 12 || 'you need 12 characters',
      },
    };
  },
  methods: {
    async somemethod() {
    //do something
    },
  },
});
</script>

任何帮助将不胜感激!!!

【问题讨论】:

  • 鉴于 .length 唯一出现在 id 规则中,我会说这是用 undefined 调用的,因此将其更改为 id: (value: string) =&gt; (value &amp;&amp; value.length === 12) || 'you need 12 characters' 应该可以解决问题。跨度>

标签: javascript typescript vue.js nuxt.js vuetify.js


【解决方案1】:

只是改变

id: (value: string) => value.length == 12 || 'you need 12 characters'

id: (value: string) => value && value.length == 12 || 'you need 12 characters'

【讨论】:

  • 感谢您的回答。顺便说一句,即使 id 已经初始化为“测试”,你知道为什么 value 是未定义的吗?
  • 我认为这可能是因为在 vue js 中传递数据的延迟或类似我不知道的东西......
  • 但是如果你想编写无故障代码,你应该在使用值长度之前检查值
猜你喜欢
  • 1970-01-01
  • 2015-05-08
  • 2020-06-02
  • 1970-01-01
  • 2015-02-05
  • 2017-11-25
  • 2021-02-26
  • 2018-06-18
  • 1970-01-01
相关资源
最近更新 更多