我需要销毁自定义指令中的元素,例如v-if。 (如果条件失败,则禁止创建项目。)
我正在尝试
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);
}
}
};
但是此选项不适合我。它不会中断组件的创建。
此代码从DOM中删除了一个元素,但不破坏组件实例。
答案 0 :(得分:0)
我没有选中此选项,但是from doc应该看起来像这样。
也许以后我会用更具体,更正确的答案进行编辑
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();
}
}
或者简而言之
Vue.directive('condition', function (el, binding) {
if (!test){ el.remove() }
})
除el之外,您应该将这些参数视为只读,并且永远不要修改它们。如果您需要跨钩子共享信息,建议通过元素的数据集进行共享。