今天就跟大家聊聊有關vue.js中怎么實時監聽input值的變化,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
一、vuejs 2.0中js實時監聽input
在2.0的版本中,vuejs把v-el 和 v-ref 合并為一個 ref 屬性了,可以在組件實例中通過 $refs 來調用。這意味著 v-el:my-element 將寫成這樣: ref="myElement" , v-ref:my-component 變成了這樣: ref="myComponent" 。綁定在一般元素上時,ref 指DOM元素,綁定在組件上時,ref 為一組件實例。
因為 v-ref 不再是一個指令了而是一個特殊的屬性,它也可以被動態定義了。這樣在和v-for 結合的時候是很有用的:
<p v-for="item in items" v-bind:ref="'item' + item.id"></p>
以前 v-el/v-ref 和 v-for 一起使用將產生一個DOM數組或者組件數組,因為沒法給每個元素一個特定名字?,F在你還仍然可以這樣做,給每個元素一個同樣的ref:
<p v-for="item in items" ref="items"></p>
和 1.x 中不同, $refs 不是響應的,因為它們在渲染過程中注冊/更新。只有監聽變化并重復渲染才能使它們響應。另一方面,設計$refs主要是提供給 js 程序訪問的,并不建議在模板中過度依賴使用它。因為這意味著在實例之外去訪問實例狀態,違背了 Vue 數據驅動的思想。
下面給一個vuejs2.0版本的例子:
<div id="example">
<input type="text" v-model="items.type1" ref="type1"/>
<input type="text" v-model="items.type2" ref="type2"/>
<div class="show">輸入框一的內容:{{items.type1}}</div>
<div class="show">輸入框二的內容:{{items.type2}}</div>
</div>
<script>
var example1 = new Vue({
el: '#example',
data: {
items: {
type1:'第一個輸入框',
type2:'第二個輸入框'
}
},
ready:function(){
},
watch:{
items:{
handler:function(val,oldval){
console.log(this.$refs.type1.value);
console.log(this.$refs.type2.value);
},
deep:true
}
},
methods:{
}
})
</script>結果如圖所示:

當在輸入框輸入文字的時候,js可以實時監聽其指定輸入框文本的值。
二、vuejs 1.x中js實時監聽input
那么在vuejs 1.x的版本中是如何在js中監聽某個指定的input的value變化的呢?
通過如下方式:
<input type="text" v-model="items.type1" v-el:texttype1/>
然后在vuejs中的watch中監聽:
watch:{
items:{
handler:function(val,oldval){
console.log(this.$els.texttype1.value);
},
deep:true
}
}整體代碼:
<div id="example">
<input type="text" v-model="items.type1" v-el:texttype1/>
<input type="text" v-model="items.type2" v-el:texttype2/>
<div class="show">輸入框一的內容:{{items.type1}}</div>
<div class="show">輸入框二的內容:{{items.type2}}</div>
</div>
<script>
var example1 = new Vue({
el: '#example',
data: {
items: {
type1:'第一個輸入框',
type2:'第二個輸入框'
}
},
ready:function(){
},
watch:{
items:{
handler:function(val,oldval){
console.log(this.$els.texttype1.value);
},
deep:true
}
},
methods:{
}
})
</script>實現的效果如圖所示:

看完上述內容,你們對vue.js中怎么實時監聽input值的變化有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。