2017-03-24 55 views
3

我正在写vue的自定义指令。自定义指令类似于v-如果在vuejs

我希望它能像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之外的另一种方式,因为它也必须从DOM中删除,例如v-if

回答

3

尝试使用这个技巧:

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错误。

+0

这是一个很好的答案,但它会在控制台中显示'不能设置属性'$ el'undefined'。 – EasonBlack

+0

它工作的很好,当我删除vnode.componentInstance。$ el = comment; 在我的情况下,因为componentInstance未定义。 谢谢 – EasonBlack