8

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.

enter image description here

this code removes an element from DOM, but not destroy a component instance.

Mgorunuch
  • 647
  • 1
  • 5
  • 16

1 Answers1

-1

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.

tony19
  • 125,647
  • 18
  • 229
  • 307
pery mimon
  • 7,713
  • 6
  • 52
  • 57
  • 3
    I might be wrong, but with all due respect, I don't think this really answers the question. The OP mentioned that the desired functionality is to prevent the DOM element to be created if the condition is not met (e.g. prevent an image from loading, similar to what would happen if using a `v-if` directive). This answer removes the element, but the image resource would have been already loaded. – Charmander Aug 17 '19 at 10:57
  • I can second @Charmander. It works visually, not even flickering, but any resources that would have been created, would remain in memory, and maybe even using compute resources. – Marcel Jul 08 '23 at 12:18