A custom directive similar to v-if in vuejs

喜欢而已 提交于 2019-12-03 10:16:41

Try to use this hack:

Vue.directive('permission', (el, binding, vnode) => {
  if (!isUserGranted(binding.value)) {
    // replace HTMLElement with comment node
    const comment = document.createComment(' ');
    Object.defineProperty(comment, 'setAttribute', {
      value: () => undefined,
    });
    vnode.elm = comment;
    vnode.text = ' ';
    vnode.isComment = true;
    vnode.context = undefined;
    vnode.tag = undefined;
    vnode.data.directives = undefined;

    if (vnode.componentInstance) {
      vnode.componentInstance.$el = comment;
    }

    if (el.parentNode) {
      el.parentNode.replaceChild(comment, el);
    }
  }
});

UPD 05-19-2017: My latest code. I define setAttribute() and check for vnode.componentInstance to prevent js errors when using with both html elements and Vue components.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!