在自定义指令中模拟 v-if 指令 [英] Simulate v-if directive in custom directive
问题描述
我需要销毁像 v-if 这样的自定义指令中的元素.(如果条件失败,则禁止创建项目.)
我正在尝试这个
export const moduleDirective: DirectiveOptions |DirectiveFunction = (el, binding, vnode) =>{const moduleStatus = store.getters[`permissions/${binding.value}Enabled`];如果(!模块状态){const comment = document.createComment(' ');Object.defineProperty(comment, 'setAttribute', {值:() =>不明确的,});vnode.elm = 评论;vnode.text = ' ';vnode.isComment = true;vnode.context = 未定义;vnode.tag = 未定义;如果(el.parentNode){el.parentNode.replaceChild(comment, el);}}};
但是这个选项不适合我.它不会中断组件的创建.
此代码从 DOM 中删除一个元素,但不会销毁组件实例.
我没有检查这个但是 来自文档 它应该是这样的.
可能我稍后会用更具体和正确的答案对其进行编辑
Vue.directive('条件', {插入(el,绑定,vnode,oldVnode){/* 当绑定元素插入其父节点时调用(这仅保证父节点存在,不一定在文档中).*/if (!test){ el.remove() }}更新(el,绑定,vnode,oldVnode){/* 在包含组件的 VNode 更新之后调用,但可能在此之前它的孩子已经更新.*/如果 (!test()){ el.remove() }//或者你可以试试这个,改变vnodevnode.props.vIf = test();}}
或者简而言之
Vue.directive('condition', function (el, binding) {if (!test){ el.remove() }})
<块引用>
除了 el 之外,您应该将这些参数视为只读的并且永远不要修改它们.如果需要跨钩子共享信息,建议通过元素的数据集来实现.
I need to destroy element in custom directive like v-if. (Forbid item creation if the condition fails.)
I trying this
export const moduleDirective: DirectiveOptions | DirectiveFunction = (el, binding, vnode) => {
const moduleStatus = store.getters[`permissions/${binding.value}Enabled`];
if (!moduleStatus) {
const comment = document.createComment(' ');
Object.defineProperty(comment, 'setAttribute', {
value: () => undefined,
});
vnode.elm = comment;
vnode.text = ' ';
vnode.isComment = true;
vnode.context = undefined;
vnode.tag = undefined;
if (el.parentNode) {
el.parentNode.replaceChild(comment, el);
}
}
};
But this option does not suit me. It does not interrupt the creation of the component.
this code removes an element from DOM, but not destroy a component instance.
I'm not checked this but from doc it should look like this.
probably I will edit it later with a more specific and correct answer
Vue.directive('condition', {
inserted(el, binding, vnode, oldVnode){
/* called when the bound element has been inserted into its parent node
(this only guarantees parent node presence, not necessarily in-document). */
if (!test){ el.remove() }
}
update(el, binding, vnode, oldVnode ){
/* called after the containing component’s VNode has updated, but possibly before
its children have updated. */
if (!test()){ el.remove() }
//or you can try this, changed the vnode
vnode.props.vIf = test();
}
}
Or in short
Vue.directive('condition', function (el, binding) {
if (!test){ el.remove() }
})
Apart from el, you should treat these arguments as read-only and never modify them. If you need to share information across hooks, it is recommended to do so through element’s dataset.
这篇关于在自定义指令中模拟 v-if 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!