一个类似于vuejs中的v-if的自定义指令 [英] A custom directive similar to v-if in vuejs

查看:938
本文介绍了一个类似于vuejs中的v-if的自定义指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在vue中编写自定义指令.

I'm writing a custom directive in vue.

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

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="PermissionFoo">Do Foo</button>

它将检查权限,并显示或隐藏该组件.

It will check the permission and will show or hide the component.

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

Currently I'm doing this via CSS styles:

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中删除.

But I don't want this element to stay in the document. So I'm looking for another way other than CSS because it must be also removed from DOM like v-if does.

推荐答案

尝试使用此技巧:

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 2017年5月19日:我的最新代码.我定义了setAttribute()并检查了vnode.componentInstance,以防止在同时使用html元素和Vue组件时出现js错误.

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.

这篇关于一个类似于vuejs中的v-if的自定义指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆