javascript - 收到此错误:无法读取未定义的属性“长度”
问题描述
我正在用 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>
任何帮助,将不胜感激!!!
解决方案
只是改变
id: (value: string) => value.length == 12 || 'you need 12 characters'
到
id: (value: string) => value && value.length == 12 || 'you need 12 characters'
推荐阅读
- gulp - 添加浏览器同步时,gulp watch 不起作用
- android - Android Runtime.exec(“screencap”)没有做任何事情(不工作)并且没有给出任何错误
- llvm - 正确使用 LLVM IRBuilder::CreateGEP
- sql - 如何根据第一个字符是否为字母来选择输出长度?
- spring - 使用 Spring WebFlux 在反应式应用程序中记录 aop 进行重复查询
- php - 将隐藏值链接/关联到表单上的特定单选按钮 (PHP/MySQL/HTML)
- rxjs - rxjs 将数组转换为 Observable 数组以进行并行执行(使用 forkJoin)?
- parameters - 嵌入 Tableau 时是否可以使用 OAuth 参数化与不同 Snowflake DB 的连接?
- c - 输入插入的整数对的顺序
- c++ - 意外的 sscanf 结果