jibzy
jibzy

Reputation: 553

How to get array length in vuejs

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

Upvotes: 0

Views: 4862

Answers (3)

Mauli999
Mauli999

Reputation: 26

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

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

Upvotes: 0

jibzy
jibzy

Reputation: 553

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

Upvotes: 1

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.

Upvotes: 1

Related Questions