• Vue思考题_01v-for与v-if的优先级谁更高


    目录


    在这里插入图片描述

    官方文档上说不推荐将v-for与v-if在同一个标签上使用,因为两者优先级并不明显。

    那么到底是那个指令的优先级比较高呢? 在vue2与vue3中答案是相反的。

    vue2

    在vue2中将2个指令放在同一个标签上

    <template>
      <ul>
        <li v-for="item in list" :key="item.key" v-if="item.key!=2">{{ item.name }}</li>
      </ul>
    </template>
    
    <script>
    export default {
      name: 'App',
      data(){
        return{
          list:[
            {
              key: '1', 
              name: 'item1'
            },
            {
              key: '2', 
              name: 'item2'
            },
            {
              key: '3', 
              name: 'item3'
            }
          ]
        }
      }
    }
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    eslint会提示不建议将两个指令放在同一个标签上

     The 'list' 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'
    
    • 1

    其实是因为在vue2中v-for比v-if的优先级高,当v-for与v-if在同一个标签上时,会先循环然后再进行if判断造成性能浪费。

    vue3

    在vue3中将2个指令放在同一个标签上:

    <template>
      <ul>
        <li v-for="item in list" :key="item.key" v-if="item.key!=2">{{ item.name }}</li>
      </ul>
    </template>
    
    <script>
    export default{
      setup(){
        const list = [
          {
            key: '1', 
            name: 'item1'
          },
          {
            key: '2', 
            name: 'item2'
          },
          {
            key: '3', 
            name: 'item3'
          }
        ]
        return{
          list
        }
      }
    }
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    在这里插入图片描述

    报错:Cannot read properties of undefined (reading ‘key’)

    原因:在vue3中 v-if的优先级高于v-for,v-if 的条件将无法访问到 v-for 作用域内定义的变量别名。

    相当于先执行v-if=‘item.key != 2’ 此时还没有执行v-for指令,item相当于为undefiend,通过点语法访问undefined的属性值自然就会报错啦。

  • 相关阅读:
    vue3 keepalive跳转页面保存页面状态
    Tainted kernels
    力扣刷题记录162.1-----127. 单词接龙
    MacOS Anaconda 安装教程及虚拟环境创建
    人工智能学习01--errors
    spring cloud之负载均衡
    Maya 2023安装步骤(附安装、汉化、图文教程)
    C++in/out输入输出流[IO流]
    1513_人月神话阅读笔记_再论没有银弹
    HDU 6277 Higher h-index
  • 原文地址:https://blog.csdn.net/qq_43260366/article/details/133748778