简体   繁体   English

如何在 vuejs 中获取数组长度

[英]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请问我做错了什么

Place this line in mounted instead of created将此行放在mounted而不是created

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

because this blog is not available in created yet that's why it is undefined.因为此博客在 created 中不可用,这就是它未定义的原因。

You can't access the object array length in mounted or created lifecycles so I just used watch property to get the object length您无法在挂载或创建的生命周期中访问 object 数组长度,所以我只是使用 watch 属性来获取 object 长度

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM