How to use .preventDefault() method to prevent button click event
P粉254077747
2023-09-01 20:04:07
<p>Given this tutorial<a href="https://vuejs.org/guide/essentials/event-handling.html#accessing-event-argument-in-inline-handlers">https:// vuejs.org/guide/essentials/event-handling.html#accessing-event-argument-in-inline-handlers</a></p>
<p>In the code shown below, I call <code>.preventDefault</code> to expect the normal behavior of canceling the <code>click</code> event. Or in other words, I expect that once <code>.preventDefault</code> is called, the button will no longer be clickable because from my understanding, <code>.preventDefault</code> will disable the button's normal functionality . </p>
<p>But what happens is that the button is still clickable, as if <code>.preventDefault</code> has no effect. </p>
<p>Please tell me how to properly use <code>.preventDefault</code> to disable button clicks. </p>
<p><strong>Code</strong>: </p>
<pre class="brush:php;toolbar:false;"><template>
<div>
<button v-on:click="warn('msg',$event)">warn</button>
</div>
</template>
<script>
import {ref} from 'vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
<script setup>
const warn = (msg,DOMEvent) => {
console.log("warn:",msg," event:",DOMEvent);
DOMEvent.preventDefault()
}
</script></pre></p>
preventDefault is useful in the following situations:
To disable the button in your case you can use:
preventDefault()
will not disable the button, but will prevent its default action, which will be mainly noticed in theSubmit
action.To disable a button on click, you need to do something like this: