vue.js - 在自定义指令中模拟 v-if 指令

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

我需要销毁自定义指令中的元素,例如 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 中删除一个元素,但不会销毁组件实例。

最佳答案

我没有检查这个但是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() }
})

Apart from el, you should treat these arguments as read-only and never modify them. If you need to share information across hooks, it is recommended to do so through element’s dataset.

关于vue.js - 在自定义指令中模拟 v-if 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53897909/

相关文章:

javascript - 使用 Vue.JS/Axios 和来自第三方 API(基于 Django!)的数据填充 DOM

javascript - 在窗口上添加 Vue.js 事件

javascript - Vue - 通过外部点击切换状态

vue.js - 如何禁用 vuejs v-table 列的排序功能?

vue.js - Vuetify - 单击时显示工具提示

javascript - 基于父组件中的 v-select 更改子组件中变量的值 (Vuetify)

vue.js - 为什么 "Error in render: TypeError: Cannot read property ' 过滤器' of undefined' 甚至返回已经可用的数据?

javascript - vuejs中如何隔离可重用的小函数

javascript - 分页和过滤分别运行/Vue

vue.js - 具有 vuetify 依赖项的 Vue 库