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

Kar*_*lom 6 javascript vue.js

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

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

我想在渲染20个单词后突破循环.我怎样才能做到这一点?我查看了文档,但没有看到任何相关内容.

cwa*_*ang 9

你可以在循环开始之前操纵数组

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


euv*_*uvl 5

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

computed: {
 shortDictionary () {
   return dictionary.slice(0, 20)
 }
}
Run Code Online (Sandbox Code Playgroud)

...

<div v-for="(word, index) in shortDictionary"> 
   <p>{{word}}</p>
</div>
Run Code Online (Sandbox Code Playgroud)


mas*_*hyu 5

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

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

  • 不再是一个好的解决方案,因为如果您在同一个 html 元素上使用 v-for 和 v-if,vue 现在会抱怨。 (3认同)