首页 > 解决方案 > 如何限制数组vuejs中显示的数据数量

问题描述

我在数据数组中有一个值列表。我想显示前两个值(0 和 1),并显示按钮 show_more。如果单击该按钮,则会显示另一组值 (2, 3),然后必须单击该按钮才能显示更多数据。

请看下面的代码:

<div id="app">
 <h2>List:</h2>
 <div v-for="(d, index) in data">
  <!-- display 0 and 1, then after a button is clicked, display 2 & 3, 
       and then a button is clicked, display 4 & 5, and so on..  -->
    {{ d }}
  </div>
</div>
<script>
new Vue({
 el: "#app",
 data() {
   return{
     data:[0,1, 2, 3, 4, 5, 6, 7, 8, 9]
   }
 }
});
</script>

标签: vue.js

解决方案


您可以使用计算方法来根据您拥有的任何条件过滤数组。

为您的数据添加限制:

data() {
  return {
    data: [...],
    limit: 2
  }
}

limit从按钮单击更新:

<button @click="limit += 2"> More </button>

返回过滤后的数据:

computed: {
 filteredData() {
   return this.data.filter( (el, index) => index < limit) )
 }
}

现在使用filteredData而不是data

<div v-for="(d, index) in filteredData">

在计算属性中包含过滤逻辑可以更容易地在将来添加更多条件。


推荐阅读