在custom指令中模拟v-if指令

问题描述 投票:0回答:1

我需要像v-if一样销毁自定义指令中的元素。 (如果条件失败,则禁止创建项目。)

我试着这个

export const moduleDirective: DirectiveOptions | DirectiveFunction = (el, binding, vnode) => {
  const moduleStatus = store.getters[`permissions/${binding.value}Enabled`];
  if (!moduleStatus) {
    const comment = document.createComment(' ');
    Object.defineProperty(comment, 'setAttribute', {
      value: () => undefined,
    });
    vnode.elm = comment;
    vnode.text = ' ';
    vnode.isComment = true;
    vnode.context = undefined;
    vnode.tag = undefined;

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

但是这个选项不适合我。它不会中断组件的创建。

enter image description here

此代码从DOM中删除元素,但不销毁组件实例。

vue.js vuejs2 vue-component vuex vue-router
1个回答
0
投票

我没有检查这个,但from doc应该看起来像这样。 可能我稍后会用更具体和正确的答案进行编辑

Vue.directive('condition', {


  inserted(el, binding, vnode, oldVnode){
    /* called when the bound element has been inserted into its parent node
      (this only guarantees parent node presence, not necessarily in-document). */

     if (!test){ el.remove() }
  }


  update(el, binding, vnode, oldVnode ){
    /* called after the containing component’s VNode has updated, but possibly before 
       its children have updated. */

     if (!test()){ el.remove() }
    //or you can try this, changed the vnode
    vnode.props.vIf = test();
  }
}

或者简而言之

Vue.directive('condition', function (el, binding) {
  if (!test){ el.remove() }
})

除了el之外,您应该将这些参数视为只读,并且永远不要修改它们。如果需要跨钩子共享信息,建议通过元素的数据集来实现。

© www.soinside.com 2019 - 2024. All rights reserved.