1、用watch方法監聽這個變量。javascript
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>hello vue</title> <script src="https://cdn.bootcss.com/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>
2、用watch監聽對象屬性。css
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/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>
3、原生js實現。html
<!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>