美文网首页vue登峰造极的Vue
v-for和v-if一起使用时的坑

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

作者: Tme_2439 | 来源:发表于2019-08-09 10:29 被阅读0次
    缘由:

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

    相关文章

      网友评论

        本文标题:v-for和v-if一起使用时的坑

        本文链接:https://www.haomeiwen.com/subject/cndcjctx.html