Home > Back-end >  How to get array length in vuejs
How to get array length in vuejs

Time:09-23

This is my script tag

<script>
export default {
  data() {
    return {
      blogs: [],    
    };
  },
  created() {
    this.paginate_total = this.blogs.length / this.paginate; 
  },   
};
</script>

these the response I get in my console

{
   
    "blogs": [
   
        {
            "_id": "63243272c988e721db51de9c",
            
        },
        {
            "_id": "63243cb8a8189f8080411e65",        
        },
      
    ]
}

error i get in my console

Cannot read properties of undefined (reading 'length')

Please what I'm I doing wrong

CodePudding user response:

Place this line in mounted instead of created

this.paginate_total = this.blogs.length / this.paginate;

because this blog is not available in created yet that's why it is undefined.

CodePudding user response:

You can't access the object array length in mounted or created lifecycles so I just used watch property to get the object length

watch: {
   blogs(blogs) {
      this.paginate_total = blogs.length / this.paginate;
   }
}
  • Related