given this tutorial https://vuejs.org/guide/essentials/event-handling.html#accessing-event-argument-in-inline-handlers
as shown below in the code, i am calling .preventDefault
expecting cancellation of the normal behaviour of the click
emitter. Or, in other words, i expect that once . preventDefault
is called the button will not be any more clickable because i think, according to my understanding,
.preventDefault
will disable the normal fucntionality of the button.
but what happens, is that the buttonn is still clickable and as if .preventDefault
has no effect.
please let me know how to disable button clicks by using .preventDefault
properly
code:
<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>
4
Answers
event.preventDefault()
stops the current event from triggering other listeners or acting on the page, essentially intercepting and killing that event.To disable a button, you can set its
disabled
attribute to true.preventDefault()
doesn’t disable the button but prevents its default action mainly you will notice in case ofSubmit
action.To disable button on click, you need to do something like this:
preventDefault can be useful when:
To disable your button in your case, you can use:
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
attributeIdeally, you’ll probably want to only disable it conditionally by using the
v-bind:
directive.