vuejs中类似v-if的自定义指令

A custom directive similar to v-if in vuejs

我正在用 vue 编写自定义指令。

我希望它像 v-if 一样工作,但它里面会有一些逻辑。让我用一个例子来解释:

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

它将检查权限并显示或隐藏组件。

目前我正在通过 CSS 样式进行此操作:

var processPermissionDirective = function (el, binding, vnode) {
    if (SOME_LOGIC_HERE) {
        el.style.display = el._display;
    }
    else {
        el.style.display = 'none';
    }
}

export default {
    bind: function (el, binding, vnode) {
        el._display = el.style.display;
        processPermissionDirective(el, binding, vnode);
    },
    update: function (el, binding, vnode) {
        processPermissionDirective(el, binding, vnode);
    }
}

但我不希望此元素保留在文档中。所以我正在寻找 CSS 以外的另一种方法,因为它也必须像 v-if 那样从 DOM 中删除。

尝试使用这个技巧:

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:我的最新代码。我定义 setAttribute() 并检查 vnode.componentInstance 以防止在与 html 元素和 Vue 组件一起使用时出现 js 错误。