我需要销毁 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 https://v2.vuejs.org/v2/guide/custom-directive.html它应该看起来像这样。
也许我稍后会用更具体和正确的答案进行编辑
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 之外,您应该将这些参数视为只读并且永远不要修改它们。如果需要跨钩子共享信息,建议通过元素的数据集来实现。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)