Vue.js 如何在vue中查找对象长度
我正在尝试使用VueJS编写表单验证 我一直在测试错误对象的长度。当我在控制台上记录它时,我一直没有定义。 我使用这个.errors.length来引用它。它似乎将.length视为错误的关键Vue.js 如何在vue中查找对象长度,vue.js,Vue.js,我正在尝试使用VueJS编写表单验证 我一直在测试错误对象的长度。当我在控制台上记录它时,我一直没有定义。 我使用这个.errors.length来引用它。它似乎将.length视为错误的关键 data(){ return { name: null, price: null, description: null, roomTypes: {}, errors: {}, } }, methods: {
data(){
return {
name: null,
price: null,
description: null,
roomTypes: {},
errors: {},
}
},
methods: {
addRoomType: function(){
if(this.name && this.description && this.price && this.this.description>10){
axios.post('/admin/room-types',{
name: this.name,
price: this.price,
description: this.description
}).then((response)=>{
this.errors = {};
this.roomTypes.push(response.data);
}).catch((error)=>{
this.errors = error.response.data;
console.error(error.response.data);
});
}
//this.errors = {};
if(!this.name){
this.errors.name = "Please enter a name.";
console.log(this.errors.name);
}
if(!this.description){
this.errors.description = "Please enter a description.";
console.log(this.errors.description);
}
if(!this.price){
this.errors.price = "Please enter a price.";
console.log(this.errors.price);
}
if(this.errors.length){
console.log(this.errors.length);};
我希望能够获取errors对象的大小,以便检查它是否为空。尝试使用object.keysthis.errors.length
不过,为了更好地管理,我建议将错误设置为数组,并将错误存储为对象数组
比如:
常量myErrors=[
{name:'First name',消息:'name是必需的'},
{name:'Email',message:'Email必须有效'}
]
这是一个伪示例,但将错误作为数组执行可以让您轻松地循环它们,并避免可能来自对象键的名称冲突。只是个主意 首先,.length仅适用于数组,但errors是一个对象,而不是数组
其次,我认为错误或房间类型的指定在代码的这一部分中不起作用:
axios.post('/admin/room-types',{
name: this.name,
price: this.price,
description: this.description
}).then((response)=>{
this.errors = {};
this.roomTypes.push(response.data);
}).catch((error)=>{
this.errors = error.response.data;
console.error(error.response.data);
});
响应和错误处理程序都是自己的函数,它们可能没有将其定义为与方法相同的Vue对象。相反,在变量self中保留对Vue对象的引用,并在处理程序中使用该引用来分配值:
var self = this;
axios.post('/admin/room-types',{
name: this.name,
price: this.price,
description: this.description
}).then((response)=>{
self.errors = {};
self.roomTypes.push(response.data);
}).catch((error)=>{
self.errors = error.response.data;
console.error(error.response.data);
});
通过使用this.errors.length,您正在尝试访问this.errors密钥
为了检查Javascript对象长度,可以使用object.keys
诸如此类:
if (Object.keys(this.errors).length) {
//your code here
}