[Vue.js] Input Text Element Change Event


Explanation

First we bind the value of input text element to the variable userinput via v-model:

<input type="text" v-model="userinput">

Next, we want to listen to the change event of this input text element. According to Event Handling in Vue.js Guide, I use v-on to listen to the change event of input event as follows:

<form> id="app">
  <input type="text" v-model="userinput" v-on:change="changeHandler">
</form>

var app = new Vue({
  el: '#app',
  data: {
    userinput: ''
  },
  methods: {
    changeHandler: function(event) {
      // change of userinput, do something
    }
  }
})

But the code does not work. changeHandler does not run. Then I do some googling [1], I found that the correct way is to use watchers:

The correct way to listen to change event(onchange) of input element is:

<form> id="app">
  <input type="text" v-model="userinput">
</form>

var app = new Vue({
  el: '#app',
  data: {
    userinput: ''
  },
  watch: {
    userinput: function(val, oldVal) {
      // change of userinput, do something
    }
  }
})

Demo & Full Example

I write a simple demo to show how to monitor the change event of input text element in Vue.js.

Demo

index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
  <title>[Vue.js] Input Change Event</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="initial-scale=1, minimal-ui" />
</head>
<body style="text-align: center;">

<div id="app">
  <form>
    <input type="text" autocomplete="off" v-model="userinput">
  </form>
  <div>value: {{ value }}</div>
  <div>old value: {{ oldValue }}</div>
</div>

<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<script src="app.js"></script>

</body>
</html>
app.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
'use strict';

var app = new Vue({
  el: '#app',
  data: {
    userinput: '',
    value: '',
    oldValue: ''
  },
  watch: {
    userinput: function(val, oldVal) {
      this.value = val;
      this.oldValue = oldVal;
    }
  }
})

Tested on:

  • Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
  • Vue.js 2.1.10.

References:

[1]

vuejs input change event - Google search

vuejs input change event - DuckDuckGo search

vuejs input change event - Bing search

vuejs input change event - Yahoo search

vuejs input change event - Baidu search

vuejs input change event - Yandex search

[2]javascript - Vuejs event on change of element value? - Stack Overflow
[3]

vuejs v-on change - Google search

vuejs v-on change - DuckDuckGo search

vuejs v-on change - Bing search

vuejs v-on change - Yahoo search

vuejs v-on change - Baidu search

vuejs v-on change - Yandex search

[4]javascript - How to fire an event when v-model changes ? (vue js) - Stack Overflow