In this tutorial, we will learn how to change button text on click. We will provide two examples to update the button text on click. To achieve this, we will use both the Composition
API and the Options API. The @click directive is used to listen to specific events and call a method when this event is triggered
How to change Button Text Dynamically?
The following code snippet uses Vue js to change the text of a button when clicked. Initially, the buttonText variable is set to “Click me” and it changes to “Button clicked!” when the button is clicked using the changeButtonText method. If you wish to add or modify more code, you can use the Tryit Editor to edit and customize the code according to your project requirements.
Vue Js Change Button Text on Click | Example
<div id="app">
<h3>Vue Js Change Button Text on click</h3>
<button @click="changeButtonText">{{ buttonText }}</button>
</div>
<script type="module">
import { createApp } from "vue";
createApp({
data() {
return {
buttonText: 'Click me'
}
},
methods: {
changeButtonText() {
this.buttonText = 'Button clicked!'
}
}
}).mount("#app");
</script>
Output of above example
In the example below, we can change the button text on click by utilizing the Composition API of Vue and ref
. With the ref
function, we were able to create a reactive reference to the button text property.
Vue Change Button Text on Click using Ref Example 2
<script type="module">
const {createApp,ref} = Vue;
createApp({
setup() {
const buttonText = ref('Click me');
const changeText = () => {
buttonText.value = 'Button Clicked';
};
return {
buttonText,
changeText
};
}
}).mount("#app");
</script>