繁体   English   中英

如何打破 vue.js 中的 v-for 循环?

[英]How to break v-for loop in vue.js?

我的 vue.js 应用程序有这个v-for循环:

  <div v-for="(word, index) in dictionary"> 
     // break if index > 20
     <p>{{word}}</p>
  </div>

我想在渲染 20 个单词后跳出循环。 我怎样才能做到这一点? 我查看了文档,但没有看到任何关于此的信息。

您可以在循环开始之前操作数组

<div v-for="(word, index) in dictionary.slice(0,20)"> 
    <p>{{word}}</p>
</div>

您必须为截断的字典创建一个计算值(例如,最好为渲染准备数据):

computed: {
 shortDictionary () {
   return dictionary.slice(0, 20)
 }
}

...

<div v-for="(word, index) in shortDictionary"> 
   <p>{{word}}</p>
</div>

对于这种情况,此解决方案最适合我。

<div v-for="(word, index) in dictionary" v-if="index <= 20"> 
    <p>{{word}}</p>
</div>

要在 v-for 级别执行此操作,请创建一个具有限制的数据对象并将其与索引进行比较以控制 v-for 和 v-if。

  <div v-for="(word, index) in dictionary" v-if="index<=limit"> 
         // break if index > 20
         <p>{{word}}</p>
</div>

    <script>
export default{
   data(){
     return{
         limit: 20 }
   }
}
</script>

由于能够将 v-for 与范围一起使用,这是一个不涉及通过拼接或使用计算创建新数组的解决方案:

<div v-for="i in Math.min(dictionary.length, 20)"> 
  <p>{{dictionary[i-1]}}</p>
</div>

https://v2.vuejs.org/v2/guide/list.html

您可以使用Array.sliceMath.min函数:

<div v-for="(word, i) in dictionary.slice(0, Math.min(20, dictionary.length))"> 
   <p>{{word}}</p>
</div>

使用计算方法:

computed: {
 firtsElements () {
   return this.dictionary.slice(0, Math.min(20, this.dictionary.length))
 }
}

暂无
暂无

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

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