我需要销毁自定义指令中的元素,例如 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 中删除一个元素,但不会销毁组件实例。
最佳答案
我没有检查这个但是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() }
})
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.
关于vue.js - 在自定义指令中模拟 v-if 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53897909/