javascript 如何禁用 vue 组件中的链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49504111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I disable a link in the vue component?
提问by Success Man
My html like this :
我的 html 是这样的:
<div id="app">
<a class="btn btn-danger" href="javascript:" @click="add($event)">add</a>
</div>
My javascript like this :
我的 javascript 是这样的:
var vue = new Vue({
el: '#app',
methods: {
add(event) {
event.target.disabled = true
}
}
});
Demo and full code like this : https://jsfiddle.net/q7xcbuxd/221/
演示和完整代码如下:https: //jsfiddle.net/q7xcbuxd/221/
I try like that. But if I click button add, it's not disabled
我就这样试试。但是如果我点击按钮添加,它不会被禁用
How can I solve this problem?
我怎么解决这个问题?
回答by acdcjunior
Since you are using boostrap, the proper way to disable a (anchor) button is not to set .disabled = true, but to add a disabledclass.
由于您使用的是 boostrap,因此禁用(锚点)按钮的正确方法不是设置.disabled = true,而是添加disabled类。
Two other notes. You probably want to prevent the default behavior of the clickevent, so use @click.prevent. Also, if you don't have additional arguments, you don't need to use ="add($event)", just ="add"will suffice.
另外两个笔记。您可能希望阻止click事件的默认行为,因此请使用@click.prevent. 此外,如果您没有其他参数,则不需要使用="add($event)",就="add"足够了。
Demo below:
演示如下:
new Vue({
el: '#app',
methods: {
add(event) {
event.target.className += ' disabled'
}
}
})
body { padding: 10px }
<script src="https://unpkg.com/vue"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<div id="app">
<a class="btn btn-danger" href="javascript:" @click.prevent="add">add</a>
</div>
You can also go pureVue and use a class binding:
您还可以使用纯Vue 并使用类绑定:
new Vue({
el: '#app',
data: {
btnDisabled: false
},
methods: {
add(event) {
this.btnDisabled = true; // mutate data and let vue disable the element
}
}
})
body { padding: 10px }
<script src="https://unpkg.com/vue"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<div id="app">
<a class="btn btn-danger" href="javascript:" @click.prevent="add" :class="{disabled: btnDisabled}">add</a>
</div>
回答by Jacob Goh
回答by Elpedio Jr. Adoptante
Add an event to your element and preventDefault.
将事件添加到您的元素并防止默认。
Then, add a custom css class that would grayed out the button and with disabled mouse cursor, and bind that class to your element.
然后,添加一个自定义 css 类,该类会使按钮变灰并禁用鼠标光标,并将该类绑定到您的元素。
CSS:
CSS:
.disabled {
cursor: not-allowed;
color: gray
}
HTML:
HTML:
<a href="" @click.prevent="add" :class="disabledClass" >Add</a>
JS:
JS:
computed: {
disabledClass: () => {
return isAddButtonDisabled ? "disabled" : ""
}
}

