Simulate v-if directive in custom directive

Viewed 1631

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.

1 Answers

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.

Related