v-for和v-if一起使用时的坑


原文:https://www.jianshu.com/p/b84f923e511e

缘由:

在进行项目开发的时候因为在一个标签上同时使用了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会重复运行在每个v-for中。

正确写法:使用template标签进行包裹(template为html5的新标签,无特殊含义)
<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值写在包裹的元素中



作者:zhulijun_
链接:https://www.jianshu.com/p/b84f923e511e
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM