首页 > 编程技术 > js

解决v-if 与 v-for 同时使用报错的问题

发布时间:2022-3-29 14:03 作者:辉太狼`

在进行项目开发的时候因为在一个标签上同时使用了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>

到此这篇关于v-if 与 v-for 同时使用会报错的文章就介绍到这了,更多相关v-if 与 v-for 使用报错内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://www.cnblogs.com/HuiTaiLang1216/p/16070218.html

标签:[!--infotagslink--]

您可能感兴趣的文章: