【问题标题】:How to break v-for loop in vue.js?如何打破 vue.js 中的 v-for 循环?
【发布时间】:2018-01-07 20:17:35
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

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

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

    【讨论】:

    • 这将适用于数组,但不适用于对象。如果它很简单,我会自己使用这种方法,但如果有比这更多的逻辑或者如果它是一个对象,我会使用计算方法。
    【解决方案2】:

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

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

    【讨论】:

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

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

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

    ...

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

    【讨论】:

    • 好点。但是出于好奇,我还是想知道v-for级别有什么办法吗?
    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2018-06-14
        • 2019-02-04
        • 1970-01-01
        • 1970-01-01
        • 2014-04-04
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多