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