Vue2 自定义指令,用于有条件地禁用按钮



我正在尝试创建一个自定义指令来有条件地禁用按钮。目前我的 html 看起来像这样:

<button v-if="someConditionIsTrue" @click="doTheThing">Do something</button>
<button v-else class="disabled">Do something</button>

禁用类只是应用一些样式。

它工作正常,但我希望 html 看起来像这样:

<button v-disable-if="someConditionIsTrue" @click="doTheThing">Do something</button>

这是一个有效的代码笔,我只需在按钮上设置禁用标志即可做到这一点。

https://codepen.io/stevgouws/pen/yRGerW

但是,这显然是不安全的,因为他们可以在开发工具中进行编辑。

这是我使用 @click.native 和 e.preventDefault 完成的另一个,但如果条件发生变化,我不知道如何管理恢复点击功能。

Vue.directive('disableIf', {
bind(el, binding, vnode) {
if (binding.value) {
el.classList.add("disabled")
el.onclick = e => {
if (binding.value) e.preventDefault()
}  
} else {
el.classList.remove("disabled")
}
},
update(el, binding, vnode) {
if (binding.value) {
el.classList.add("disabled")
el.onclick = e => {
if (binding.value) e.preventDefault()
}        
} else {
el.classList.remove("disabled")
}
}
});

代码笔在这里-> https://codepen.io/stevgouws/pen/JmwXGE

任何帮助将不胜感激。

您可以使用:disabled="someCondition"hmtl 属性直接禁用该按钮,而无需自定义指令。请注意使用:,以便它绑定到 VM 的someCondition属性。

使用您的示例:

<div id="app">
<button :disabled="someCondition" @click="doTheThing">Do the thing</button>
<button @click="someCondition = !someCondition">Toggle Condition</button>
</div>

并使用button:disabledcss 选择器来应用您的样式。

button:disabled {
opacity: 0.4;
}

这是你的笔 https://codepen.io/dormenog/pen/jeXqYO?editors=0100 叉。

关于防止 click 事件,可以使用与条件相同的属性来阻止 click 事件处理程序继续。例如

doTheThing($event) {
if (this.someCondition) {
return;
}
//do stuff
}

在 Vue 应用程序的生产版本中,你不应该有权访问开发工具。用户可能会通过 DOM 启用按钮,但方法中的条件会阻止操作继续。

请记住,您可以在任何本机支持它的 html 元素(即输入字段、锚标记和文本区域(中使用:disabled="foo"绑定。

我试图做同样的事情,我想我找到了一个简单而"优雅"的解决方案。

Wrapper.vue

<template>
<div>
<slot :disabled="disabledModel" />
</div>
</template>
<script>
export default {
name: 'Role',
data: () => ({
disabledModel: false,
}),
computed: {
disabled: {
get() {
return this.disabledModel
},
set(value) {
this.disabledModel = value
},
},
},
}
</script>

main.js- 指令 ...

Vue.directive('wrapper', {
bind: function (el, binding, vnode) {
vnode.componentOptions.propsData.disabled = true //here
}
}

在我的组件中

<wrapper v-wrapper v-slot="slotProps">
<v-btn
color="primary"
v-bind="slotProps"
>
Something
</v-btn>
</wrapper>

最新更新