溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何解決v-if與v-for同時(shí)使用報(bào)錯(cuò)的問(wèn)題

發(fā)布時(shí)間:2022-03-29 11:46:05 來(lái)源:億速云 閱讀:604 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了如何解決v-if與v-for同時(shí)使用報(bào)錯(cuò)的問(wèn)題,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

在進(jìn)行項(xiàng)目開(kāi)發(fā)的時(shí)候因?yàn)樵谝粋€(gè)標(biāo)簽上同時(shí)使用了v-for和v-if兩個(gè)指令導(dǎo)致的報(bào)錯(cuò)。

報(bào)錯(cuò)代碼如下:

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

提示錯(cuò)誤: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)先級(jí)比 v-if 的高,所以每次渲染時(shí)都會(huì)先循環(huán)再進(jìn)條件判斷,而又因?yàn)?v-if 會(huì)根據(jù)條件為 true 或 false來(lái)決定渲染與否的,所以如果將 v-if 和 v-for一起使用時(shí)會(huì)特別消耗性能,如果有語(yǔ)法檢查,則會(huì)報(bào)語(yǔ)法的錯(cuò)誤。

1. 將 v-for 放在外層嵌套 template (頁(yè)面渲染不生成 DOM節(jié)點(diǎn)) ,然后在內(nèi)部進(jìn)行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>

注意點(diǎn):key值寫(xiě)在包裹的元素中

2. 如果條件出現(xiàn)在循環(huán)內(nèi)部,不得不放在一起,可通過(guò)計(jì)算屬性computed 提前過(guò)濾掉那些不需要顯示的項(xiàng)

<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: {//通過(guò)計(jì)算屬性過(guò)濾掉列表中不需要顯示的項(xiàng)目
    activeUsers: function () {
      return this.users.filter(function (user) {
        return user.isShow;//返回isShow=true的項(xiàng),添加到activeUsers數(shù)組
      })
    }
  }
};
</script>

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“如何解決v-if與v-for同時(shí)使用報(bào)錯(cuò)的問(wèn)題”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI