vue的v-for和v-if同时使用解决方法

158 阅读1分钟

在源码中我们知道,在vue2,v-for优先级更高;vue3,v-if优先级更高。如果两个同时使用,每次循环都会执行判断,当数据量很大时,很消耗性能,所以不要一起使用。如果要,可以这样解决:

一、把 v-if 改为 v-show

二、使用computed提供新的数组去循环。

<div v-for="item in showList">{{item}}</div>


data() {
  return {
    items: ['1', '2', '3', '1', '1']
  }
}
// showList提供v-if判断里满足条件的元素数组
computed: {
  showList: function() {
    return this.items.filter(el => { return el === '1' })
  }
}

三、用一层template把它包起来

<template v-for="item in items">
  <div v-if="item==='1'">{{item}}</div>
</template>