美文网首页
v-if和v-for谁的优先级更高

v-if和v-for谁的优先级更高

作者: 没有昵_称 | 来源:发表于2020-12-29 15:24 被阅读0次
    • 两者同级
    //html
    <p v-for="item in list" :key="item.title" v-if="item.show">{{item.title}}</p>
    //js
    data(){
     return{
      list: [
        { title: 'nihao', show: false },
        { title: 'nihao2', show: true},
      ];
    }}
    

    渲染函数如下

    //执行 vm.$options.render
    
    var render = function() {
      var _vm = this
      var _h = _vm.$createElement
      var _c = _vm._self._c || _h
      return _c(
        "div",
        { staticClass: "Contact" },
        _vm._l(_vm.list, function(item) {
          return item.show
            ? _c("p", { key: item.title }, [_vm._v(_vm._s(item.title))])
            : _vm._e()
        }),
        0
      )
    }
    

    _c创建元素的虚拟节点
    _v 创建文本的虚拟节点
    _s JSON.stringify
    _l是循环list的函数,item.show在每循环执行的函数中判断是否创建虚拟dom

    • v-if在外层时
    //html
    <template v-if="show">
      <p v-for="item in list" :key="item.title" >{{item.title}}</p>
    </template>
    //js
    data(){
     return{
      show: true,
      list: [
        { title: 'nihao', show: false },
        { title: 'nihao2', show: true},
      ];
    }}
    

    渲染函数如下

    //执行 vm.$options.render
    var render = function() {
      var _vm = this
      var _h = _vm.$createElement
      var _c = _vm._self._c || _h
      return _c(
        "div",
        { staticClass: "Contact" },
        [
          _vm.show
            ? _vm._l(_vm.list, function(item) {
                return _c("p", { key: item.title }, [_vm._v(_vm._s(item.title))])
              })
            : _vm._e()
        ],
        2
      )
    }
    

    他会先判断vm.show,再去循环列表

    所以v-forv-if的优先级更高,(源码在处理AST的时候,会先处理for,在处理if)

    image.png
    如果v-forv-if同时出现时,每次渲染都会先去循环再去判断,浪费了性能

    如何规避,在外层套个template,在template这层做v-if判断,
    如果是根据数据中的字段去判断是否显示,可以用计算属性先过滤掉影藏的数据再去v-for循环数据

    相关文章

      网友评论

          本文标题:v-if和v-for谁的优先级更高

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