100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > vue实现实时监听文本框内容的变化(最后一种为原生js)

vue实现实时监听文本框内容的变化(最后一种为原生js)

时间:2018-08-16 20:07:07

相关推荐

vue实现实时监听文本框内容的变化(最后一种为原生js)

一、用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>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。