gpt4 book ai didi

vuejs2 - 一个类似于 vuejs 中 v-if 的自定义指令

转载 作者:行者123 更新时间:2023-12-03 14:12:27 25 4
gpt4 key购买 nike

我正在 vue 中编写自定义指令。

我希望它像 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做。

最佳答案

尝试使用这个黑客:

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 : 我的最新代码。我定义 setAttribute()并检查 vnode.componentInstance在与 html 元素和 Vue 组件一起使用时防止 js 错误。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com