如何在Vue中查找对象长度

时间:2019-07-19 21:08:03

标签: vue.js

我正在尝试使用VueJS编写表单验证。

我一直在测试错误对象的长度。当我登录控制台时,我一直处于未定义状态。 我用this.errors.length来引用它。似乎将.length视为错误的关键。

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);};

我希望能够获取错误对象的大小,以便我可以检查它是否为空。

3 个答案:

答案 0 :(得分:1)

尝试使用Object.keys(this.errors).length

尽管为了更好的管理,我还是建议将错误数组化并将错误存储为对象数组。

类似的东西:

const myErrors = [ { name: ‘First name’, message: ‘Name is required’ }, { name: ‘Email’, message: ‘Email must be valid’ } ]

这是一个伪示例,但通过将数组作为错误可以使您轻松地循环它们,并避免对象键可能引起的名称冲突。只是一个主意!

答案 1 :(得分:0)

首先,.length仅适用于数组,但是errors是一个对象,而不是数组。

第二,我认为errorsroom types的分配不适用于代码的这一部分:

        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);
        });

response-和error处理函数是自己的函数,可能没有为您的方法将this定义到同一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);
        });

答案 2 :(得分:-1)

通过使用this.errors.length,您正在尝试访问this.errors密钥。

要检查Javascript对象的长度,可以使用 Object.keys

类似的东西:

if (Object.keys(this.errors).length) {
   //your code here
}