v-if 與 v-for 同時使用會報錯
阿新 • • 發佈:2022-03-29
在進行專案開發的時候因為在一個標籤上同時使用了v-for和v-if兩個指令導致的報錯。
報錯程式碼如下:
<el-input type="textarea" :autosize="{ minRows: 2, maxRows: 8}" v-for="Oitem in Object.keys(cItem)" :key="Oitem" v-if="Oitem !== 'title'" v-model="cItem[Oitem]"> </el-input>
提示錯誤:The 'undefined' variable inside 'v-for' directive should be replaced with a computed property that returns filtered array instead. You should not mix 'v-for' with 'v-if'
原因:v-for 的優先順序比 v-if 的高,所以每次渲染時都會先迴圈再進條件判斷,而又因為 v-if 會根據條件為 true 或 false來決定渲染與否的,所以如果將 v-if 和 v-for一起使用時會特別消耗效能,如果有語法檢查,則會報語法的錯誤。
1. 將 v-if 放在外層巢狀 template (頁面渲染不生成 DOM節點),在這一層進行 v-if 判斷,然後在內部進行 v-for 迴圈
2. 如果條件出現在迴圈內部,不得不放在一起,可通過計算屬性computed 提前過濾掉那些不需要顯示的項
<template v-for="Oitem in Object.keys(cItem)"> <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 8}" :key="Oitem" v-if="Oitem !== 'title'" v-model="cItem[Oitem]"> </el-input> </template>
注意點:key值寫在包裹的元素中