In this tutorial, we will learn how to use Vue.js to capture input change values. The onchange event in Vue.js is an event handler triggered when the value of an element changes. For example, when a user types into an input text field, the onchange event is triggered, capturing the target value. We provide two examples in this tutorial to cover both options and Composition API for this code.
Example 1 : Vue Get Input Value on Change
In this example, we use the Vue Options API to obtain the value of the input field during the onchange event. This implies that the myInput function is triggered when there are changes in the input field’s value.
Vue Input Change Event (Options Api)
<div id="app">
<h3>Vue Js @onchange Event </h3>
<input @change="myInput" />
</div>
<script type="module">
const app = new Vue({
el: "#app",
methods: {
myInput(event) {
alert(event.target.value)
}
}
});
</script>
Output of Input Trigger Change Event
This is the second example in which we use the Vue 3 Composition API to retrieve the value of the input when the user enters some text in the text field. We use ‘ref’ and some functions to achieve this functionality.
Vue 3 Input on Change Event (Composition API)
<script type="module">
const {createApp,ref} = Vue;
createApp({
setup() {
const inputValue = ref('');
const handleInputChange = () => {
console.log('Input changed:', inputValue.value);
};
return {
inputValue,
handleInputChange
};
}
}).mount("#app");
</script>