In this section we will how to use click event in vuejs 3 composition api.
Example 1
Simple Composition Api Click Event.
Vue
<template>
<div class="container mx-auto">
<p>{{ count }}</p>
<button @click="count++" class="px-4 py-2 text-blue-900 bg-blue-100">
Increment
</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
return { count };
},
};
</script>
Vue 3 composition api method click event.
Vue
<template>
<div class="container mx-auto">
<p>{{ count }}</p>
<button @click="Increment" class="px-4 py-2 text-blue-900 bg-blue-100">
Increment
</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
const Increment = () => count.value++
return { count, Increment };
},
};
</script>
Example 2
Show and hide div element using vuejs 3 composition api.
Vue
<template>
<div class="container mx-auto">
<button @click="showElement" class="px-4 py-2 text-white bg-indigo-600">
Click
</button>
<div v-show="message">vue show component on click</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const message = ref(false);
function showElement() {
message.value = !message.value;
}
return { message, showElement };
},
};
</script>
Example 3
Vue 3 composition api click event simple function argument with arrow function.
Vue
<template>
<div class="container flex justify-center mx-auto">
<div class="mt-20 space-x-4">
<button
@click="sayHi('Vue 3 Composition Api is Awesome!')"
class="px-4 py-2 text-blue-900 bg-blue-100"
>
Sayhi
</button>
<button
@click="sayBye('Bye Bye!')"
class="px-4 py-2 text-red-900 bg-red-100"
>
SayBye
</button>
</div>
</div>
</template>
<script>
import { ref } from "vue";
export default {
setup() {
// Define a ref for message
const message = ref("");
// Define functions to handle button clicks
const sayHi = (message) => alert(message);
const sayBye = (message) => alert(message);
return { message, sayHi, sayBye };
},
};
</script>