How to use .preventDefault() method to prevent button click event
P粉254077747
P粉254077747 2023-09-01 20:04:07
0
2
567
<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>
P粉254077747
P粉254077747

reply all(2)
P粉002023326

preventDefault is useful in the following situations:

  • Prevent form submission when clicking the "Submit" button
  • When a link is clicked, prevent the link from jumping to the URL

To disable the button in your case you can use:

const warn = (msg,DOMEvent) => {
  DOMEvent.srcElement.disabled = true;
}
P粉726234648

preventDefault() will not disable the button, but will prevent its default action, which will be mainly noticed in the Submit action.
To disable a button on click, you need to do something like this:

<template>
  <div>
      <button :disabled="isDisabled" 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() //uncomment if needed
      this.isDisabled = true;
    }
</script>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template