一、用watch方法监听这个变量。
<!DOCTYPE html><html><head><meta charset="utf-8"><title>hello vue</title><script src="/vue/2.4.2/vue.min.js"></script></head><body><div id="watch-example"><p>Ask a yes/no question:<input v-model="question"></p><p>{{ answer }}</p></div><script>var watchExampleVM = new Vue({el: '#watch-example',data: {question: '',answer: 'I cannot give you an answer until you ask a question!'},watch: {// 如果 `question` 发生改变,这个函数就会运行 question: function () {this.answer = 'Waiting for you to stop typing...'alert(this.question)}}})</script></body></html>
二、用watch监听对象属性。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/vue/2.4.2/vue.min.js"></script> </head> <body> <div id="example"> <input type="text" v-model="items.type" ref="type" /> <input type="text" v-model="items.content" ref="content"><div class="show">输入框1的内容:{{items.type}}</div> <div class="show">输入框2的内容:{{items.content}}</div></div> <script> var example1 = new Vue({ el: '#example', data: { items: { type: '千年之恋:',content: '是谁在悬崖上泡一壶茶' } }, watch: { items: { handler: function() { alert(this.$refs.type.value + this.$refs.content.value); }, deep: true } } }) </script> </body> </html>
三、原生js实现。
<!DOCTYPE html><html><head><meta charset="utf-8"><title>输入监测</title><script type="text/javascript">window.onload=function(){var otxt=document.getElementById("txt");var oshow=document.getElementById("show");if(document.all){otxt.onpropertychange=function(){oshow.innerHTML=otxt.value;}}else{otxt.oninput=function(){oshow.innerHTML=otxt.value;}}}</script></head><body><div id="show"></div><input type="text" id="txt" value="测试"/></body></html>