v-show v-if v-for

1: v-if和v-show的区别

v-if

v-if 最终会被编译成三元运算符

const VueTemplateCompiler = require('vue-template-compiler');
//compile
let r1 = VueTemplateCompiler.compile(`<div v-if="true"><span v-for="i in 3">hello</span></div>`);
//编译后的结果
with(this){
  return(true)?_c('div',_l((3),function(i){
    return _c('span',[_v('hello')])
  }),0):_e()
}

v-show

编译的时候编译成指令

const VueTemplateCompiler = require('vue-template-compiler');
let r2 = VueTemplateCompiler.compile(`<div v-show="true"></div>`);

//编译结果
with(this){
  return _c('div',{
    directives:[
      {
        name:'show',
        rawName:'v-show',
        vaule:(true),
        expression:"true"
      }
    ]
  })
}

指令的编写,false,会display:none,否则为原来的属性

export default {
  bind (el: any, { value }: VNodeDirective, vnode: VNodeWithData) {
    vnode = locateNode(vnode)
    const transition = vnode.data && vnode.data.transition
    const originalDisplay = el.__vOriginalDisplay =
      el.style.display === 'none' ? '' : el.style.display
    if (value && transition) {
      vnode.data.show = true
      enter(vnode, () => {
        el.style.display = originalDisplay
      })
    } else {
      el.style.display = value ? originalDisplay : 'none'
    }
  },
    //....
}

core/instance/render-helpers/index.js

image

2: v-if和v-show为什么不能一起用

v-for的优先级会比v-if的优先级更高一些,如果连用的话,会把v-if给每个元素添加一下,会造成性能问题

const VueTemplateCompiler = require('vue-template-compiler');
let r1 = VueTemplateCompiler.compile(`<div v-if="false" v-for="i in 3">hello</div>`);
//编译后的代码
with(this){
  return _l((3),function(i){
    return (false)?_c('div',[_v("hello")]):_e()
  })
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容