如何在vue中找到对象长度

Pre*_*ang 0 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);};
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

为了检查 Javascript 对象长度,您可以使用Object.keys

类似的东西:

if (Object.keys(this.errors).length) {
   //your code here
}
Run Code Online (Sandbox Code Playgroud)