[Vuejs]-How to disable button clicks via .preventDefault()

2👍

preventDefault() doesn’t disable the button but prevents its default action mainly you will notice in case of Submit action.

To disable 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>

1👍

event.preventDefault() stops the current event from acting on the page.

To disable a button, you can set its disabled attribute to true.

button.addEventListener('click', () => {
 button.disabled = true;
 button.textContent = 'Cant touch this';
})
<button id="button">Click Me</button>

1👍

preventDefault can be useful when:

  • Clicking on a "Submit" button, prevent it from submitting a form
  • Clicking on a link, prevent the link from following the URL

To disable your button in your case, you can use:

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

0👍

Doesn’t seem like you’re using the preventDefault method correctly.

Read up on the MDN Event.preventDefault() docs for a better take on how to use it.

First off, to disable a button, you can simply use the disabled attribute

<button v-on:click="warn('msg',$event)" disabled>warn</button>

Ideally, you’ll probably want to only disable it conditionally by using the v-bind: directive.

<template>
    <div>
        <button v-on:click="warn('msg',$event)" v-bind:disabled="isDisabled">warn</button>

        <!-- A new button to toggle disabled state -->
        <button v-on:click="toggleDisabledState">Toggle</button> 
    </div>
</template>
... 

<script setup>
    import {ref} from 'vue'

    const isDisabled = ref(false);

    const warn = (msg,DOMEvent) => {
      console.log("warn:",msg," event:",DOMEvent);
    }

    // toggle method
    const toggleDisabledState = () => {
      isDisabled.value = !isDisabled.value
    } 
</script>

Leave a comment