解決v-if 與 v-for 同時使用報錯的問題
在進行項目開發(fā)的時候因為在一個標簽上同時使用了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 的優(yōu)先級比 v-if 的高,所以每次渲染時都會先循環(huán)再進條件判斷,而又因為 v-if 會根據條件為 true 或 false來決定渲染與否的,所以如果將 v-if 和 v-for一起使用時會特別消耗性能,如果有語法檢查,則會報語法的錯誤。
1. 將 v-for 放在外層嵌套 template (頁面渲染不生成 DOM節(jié)點) ,然后在內部進行v-if 判斷
<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值寫在包裹的元素中
2. 如果條件出現在循環(huán)內部,不得不放在一起,可通過計算屬性computed 提前過濾掉那些不需要顯示的項
<template>
<div>
<div v-for="(user,index) in activeUsers" :key="user.index" >{{ user.name }}</div>
</div>
</template>
<script>
export default {
name:'A',
data () {
return {
users: [{name: 'aaa',isShow: true}, {name: 'bbb',isShow: false}]
};
},
computed: {//通過計算屬性過濾掉列表中不需要顯示的項目
activeUsers: function () {
return this.users.filter(function (user) {
return user.isShow;//返回isShow=true的項,添加到activeUsers數組
})
}
}
};
</script>到此這篇關于v-if 與 v-for 同時使用會報錯的文章就介紹到這了,更多相關v-if 與 v-for 使用報錯內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue中的Object.freeze()?優(yōu)化數據方式
這篇文章主要介紹了vue中的Object.freeze()優(yōu)化數據方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04

