How to get array length in vuejs

Viewed 44

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

3 Answers

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.

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

For row counts (as for table pagination etc.) i would use a computed property like:

computed: {
  paginate_total() {
      return this.blogs.length;
  },
}
Related