繁体   English   中英

收到此错误:无法读取未定义的属性“长度”

[英]Getting this error: Cannot read property 'length' of undefined

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

我有单选按钮(比如 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 时测试数据已经初始化所以我很困惑......

这是我的简化代码:

<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>

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

只是改变

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

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

从:-

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

到:-

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

在这里,首先它会检查值,然后检查长度,如果两者都为真,那么它将变为真。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM