【问题标题】:Simulate v-if directive in custom directive在自定义指令中模拟 v-if 指令
【发布时间】:2019-05-22 16:49:04
【问题描述】:

我需要销毁自定义指令中的元素,例如 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);
    }
  }
};

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

此代码从 DOM 中删除一个元素,但不破坏组件实例。

【问题讨论】:

  • 不使用 vue 组件的渲染选项?
  • @perymimon 是的。我需要在没有初始化的情况下销毁一个元素。
  • @Mgorunuch,您找到解决问题的方法了吗?我也面临同样的事情。

标签: vue.js vuejs2 vue-component vuex vue-router


【解决方案1】:

我没有检查过这个,但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 之外,您应该将这些参数视为只读并且永远不要修改它们。如果需要跨 hooks 共享信息,建议通过 element 的 dataset 来实现。

【讨论】:

  • 我可能错了,但恕我直言,我认为这并不能真正回答问题。 OP 提到所需的功能是防止在不满足条件时创建 DOM 元素(例如,防止加载图像,类似于使用 v-if 指令时会发生的情况)。此答案删除了元素,但图像资源已经加载。
猜你喜欢
  • 2018-02-20
  • 2017-08-17
  • 2021-04-23
  • 2012-12-14
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
相关资源
最近更新 更多