- _nosay
监听input text 文本改变事件记录
2017-09-05 13:14:19
一开始的时候,使用
<input type="text" v-model="userinput" v-on:change="changeHandler">
var app = new Vue({ el: '#app', data: { userinput: '' }, methods: { changeHandler: function(event) { // change of userinput, do something } }})
在input框中输入东西的时候,并没有触发change事件,而是在失去焦点的时候触发。
最终通过watch事件达到了需求,特此记录一下,关键代码如下:
<input type="text" v-model="userinput">
var app = new Vue({ el: '#app', data: { userinput: '' }, watch: { userinput: function(val, oldVal) { // change of userinput, do something } }})
附上一个简单的demo
<!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>
var app = new Vue({ el: '#app', data: { userinput: '', value: '', oldValue: '' }, watch: { userinput: function(val, oldVal) { this.value = val; this.oldValue = oldVal; } }})