[Vue.js] 輸入元素文字改變事件


解釋

首先我們把 輸入文字元素 (input text element) 的值(value)透過 v-model 綁定 到 userinput 這個變數:

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

接著我們想要監聽這個輸入文字元素的 改變事件 。根據 Event Handling in Vue.js Guide ,我使用 v-on 來監聽輸入元素的改變事件, 如下所示:

<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
    }
  }
})

但這個程式碼不能運作。 changeHandler 並沒有執行。接著我做了一些谷歌搜尋 [1] ,我發現正確的方式是要使用 watchers:

監聽輸入元素的改變事件(onchange)正確方式是:

<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
    }
  }
})

示例及完整範例

我寫了一個簡單的示例來展示如何利用 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