v-if 與 v-for 同時使用會報錯

在進行項目開發的時候因為在一個標籤上同時使用了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-for 放在外層嵌套 template (頁面渲染不生成 DOM節點) ,然後在內部進行 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. 如果條件出現在循環內部,不得不放在一起,可通過計算屬性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>