v-if不能和v-for在同一標簽元素中使用,怎么辦?
先復習下v-if和v-for不能放在同一標簽使用的原因:
v-for 的優先級比 v-if 的高,所以每次渲染時都會先循環再進條件判斷,而又因為 v-if 會根據條件為 true 或 false來決定渲染與否的,所以如果將 v-if 和 v-for一起使用時會特別消耗性能,如果有語法檢查,則會報語法的錯誤。
如何解決這個問題呢?
1、用template放在最外層來解決這個問題。使用template是因為它不會產生新的DOM元素,降低性能的消耗。
1 <template v-for="(item, index) in payApplyFlieList"> 2 <el-descriptions-item :label="item.templateName" :key="index" v-if="item.updateFileId"> 3 <div> 4 <span>{{ item.updateFileNane }}</span> 5 </div> 6 </el-descriptions-item> 7 </template>
2. 如果條件出現在循環內部,不得不放在一起,可通過計算屬性computed 提前過濾掉那些不需要顯示的項
1 <template> 2 <div> 3 <div v-for="(user,index) in activeUsers" :key="user.index" >{{ user.name }}</div> 4 </div> 5 </template> 6 <script> 7 export default { 8 name:'A', 9 data () { 10 return { 11 users: [{name: 'aaa',isShow: true}, {name: 'bbb',isShow: false}] 12 }; 13 }, 14 computed: {//通過計算屬性過濾掉列表中不需要顯示的項目 15 activeUsers: function () { 16 return this.users.filter(function (user) { 17 return user.isShow;//返回isShow=true的項,添加到activeUsers數組 18 }) 19 } 20 } 21 }; 22 </script>

浙公網安備 33010602011771號