Subscribe on changes!

Custom Directive with removal of component

avatar
Jul 27th 2022

What problem does this feature solve?

I'm writing a custom directive in vue.

I want it to work like v-if but it will have a little logic going inside it. Let me explain with an example:

<button v-permission-show="PermissionFoo">Do Foo</button>

It will check the permission and will keep or remove the component.

app.directive('permission-show', {
  mounted(el, binding, _vnode) {
    const permissionName = binding.value;
    const defaultValue = binding.value || false;

    const permission = Permission.get(permissionName, defaultValue);
    if (!permission) {
      el.parentNode.removeChild(el);
    }
  },
});

This is what I'm currently using but it doesn't work in a lot of places.

What does the proposed API look like?

have an option in el similar to el.$destroy()

avatar
Jul 28th 2022

maybe like this, i'm not sure too.

imoprt { render } from "vue"
render(null, el);
avatar
Aug 2nd 2022

I tried that too. I get another error. Uncaught (in promise) TypeError: Cannot read properties of null (reading '_vnode')

app.directive('permission-show', {
  mounted(el, binding, _vnode) {
    const permissionName = binding.value;
    const defaultValue = binding.value || false;

    const permission = Permission.get(permissionName, defaultValue);
    if (!permission) {
       render(el, null);
    }
  },
});
avatar
Mar 31st 2023

I had the same problem. I expected to completely destroy the vnode in the beforeMount in directive, but I didn't find a way to do it @yyx990803