search

Home  >  Q&A  >  body text

How to use .preventDefault() method to prevent button click event

<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粉254077747P粉254077747454 days ago569

reply all(2)I'll reply

  • P粉002023326

    P粉0020233262023-09-02 19:15:13

    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;
    }

    reply
    0
  • P粉726234648

    P粉7262346482023-09-02 17:59:20

    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>

    reply
    0
  • Cancelreply