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
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()
})
}