<button @click.prevent="increment">Click me</button>
methods: {
increment() {
console.log('Clicked!')
}
}What is the effect of the
.prevent modifier here?The .prevent modifier calls event.preventDefault(), stopping the default browser action (like following a link). It does not stop the event from running the method or propagating.
<div @click="outer">
<button @click.stop="inner">Click me</button>
</div>
methods: {
outer() { console.log('Outer clicked') },
inner() { console.log('Inner clicked') }
}What happens when the button is clicked?
The .stop modifier calls event.stopPropagation(), which prevents the event from bubbling up to parent elements. So only the button's handler runs.
<button @click.once="count++">Click me</button>
setup() {
const count = ref(0)
return { count }
}If the user clicks the button 5 times, what is the final value of
count?The .once modifier makes the event listener run only once. After the first click, it is removed, so further clicks do not increment count.
Vue supports chaining modifiers like .prevent.stop. The order matters: .prevent then .stop is valid. .once must be alone or last. .preventOnce is invalid.
<button @click.once="increment">Click</button>
setup() {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
}After clicking the button multiple times, count only increases once. Why?
The .once modifier tells Vue to remove the event listener after it runs once. This means the increment function is called only on the first click.