A custom directive similar to v-if in vuejs

后端 未结 1 1390
猫巷女王i
猫巷女王i 2021-02-07 01:37

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:

1条回答
  •  生来不讨喜
    2021-02-07 01:42

    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.

    0 讨论(0)
提交回复
热议问题