我正在使用 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 时测试数据已经初始化,所以我是困惑...
这是我的简化代码:
<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>
任何帮助将不胜感激!!!
答案 0 :(得分:1)
只要改变
id: (value: string) => value.length == 12 || 'you need 12 characters'
到
id: (value: string) => value && value.length == 12 || 'you need 12 characters'