前言
概述
v-if 和 v-else 都是我们在日常开发中十分常用的指令,接下来就是用自定义指令的方式实现一下它们
自定义指令 v-my-show
vMyShow.js :
const vMyShow = {
mounted(el, bindings, vNode) {
const isShow = bindings.value;
if (isShow) {
el.style.display = '';
} else {
el.style.display = 'none';
}
},
updated(el, bindings, vNode) {
const isShow = bindings.value;
if (isShow) {
el.style.display = '';
} else {
el.style.display = 'none';
}
}
};
export default vMyShow;
自定义指令 v-my-if
export default {
mounted (el, bindings) {
const isShow = bindings.value;
el.commentNode = document.createComment('v-if');
!isShow && el.parentNode.replaceChild(el.commentNode, el);
},
updated (el, bindings) {
const isShow = bindings.value,
oldIsShow = bindings.oldValue;
if (isShow !== oldIsShow) {
isShow ? el.commentNode.parentNode.replaceChild(el, el.commentNode)
: el.parentNode.replaceChild(el.commentNode, el);
}
}
};