How to use@input Event in JavaScript

In this method, we are using the @input event to trigger the changeFn function when the Vue.js v-model binding changes. The changeFn function logs the new value, updates the message in the UI, and gives the message when the input is empty.

Syntax:

<input v-model="msg" @input="changeFn">

Example: Below is the implementation of the above-discussed approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>Example 1</title>
    <script src=
"https://cdn.jsdelivr.net/npm/vue@2">
      </script>
</head>
 
<body>
    <div id="app">
        <h1 style="color: green;">w3wiki</h1>
        <h3>Approach 1: Using @input Event</h3>
        <p>Value: {{ msg }}</p>
        <input v-model="msg" @input="changeFn">
        <button @click="resetBtn">Reset Msg</button>
        <p v-if="isEmpty" style="color: red;">
            Please enter a value.</p>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                msg: '',
                isEmpty: false
            },
            methods: {
                changeFn: function () {
                    console.log('Input changed! New value:',
                        this.msg);
                    this.isEmpty = this.msg.trim() === '';
                },
                resetBtn: function () {
                    this.msg = '';
                    this.isEmpty = false;
                }
            }
        });
    </script>
</body>
 
</html>


Output:

How to Fire an Event When v-model Changes ?

v-model is the two-way binding directive that mainly creates the connection between the input element and the data property. In this article, we will see how we can fire an event when the v-model directive is changed. We will see the two different approaches with the practical implementation in terms of examples.

These are the two approaches:

Table of Content

  • Using @input Event
  • Using Watcher

Similar Reads

Approach 1: Using @input Event

In this method, we are using the @input event to trigger the changeFn function when the Vue.js v-model binding changes. The changeFn function logs the new value, updates the message in the UI, and gives the message when the input is empty....

Approach 2: Using Watcher

...

Contact Us