- 實現(xiàn)文本數(shù)據(jù)變化的監(jiān)聽有兩種方式,一種是使用
@keyup
事件進(jìn)行監(jiān)聽,另外一種是使用vue
實例中使用watch字段進(jìn)行監(jiān)聽
- 存在問題:只能監(jiān)聽有dom元素的
- 使用
@keyup
進(jìn)行監(jiān)聽的寫法
<input type="text" v-model="firstname" @keyup="getfullName">+<input type="text" v-model="lastname" @keyup="getfullName">=<input type="text" v-model="fullname">
<script type="text/javascript">
const vm = new Vue({
data:{
firstname:'',
lastname:'',
fullname:''
},
methods:{
getfullName() {
this.fullname = this.firstname +'-'+this.lastname;
}
},
}).$mount('#app');
</script>
- 使用watch字段進(jìn)行監(jiān)聽
- 優(yōu)勢:能監(jiān)聽非dom元素,如:用來監(jiān)聽路由地址的變化腥沽,
'$route.path':function(newVal,oldVal){}
- 使用該字段,可以監(jiān)聽指定數(shù)據(jù)的變化徘六,然后觸發(fā)
watch
中對應(yīng)data
字段中同名屬性名的function
處理函數(shù)混槐,newVal
指代最新輸入文本,oldVal
指代上次文本框中的文本值
<input type="text" v-model="firstn">+<input type="text" v-model="lastn">= <input type="text" v-model="fulln">
<script type="text/javascript">
const vm = new Vue({
data:{
firstn:'',
lastn:'',
fulln:''
},
watch:{//firstn對應(yīng)data中的firstn
firstn(newVal,oldVal) {
this.fulln = newVal +'-'+this.lastn;
},
lastn(newVal,oldVal) {
this.fulln = this.firstn +'-'+newVal;
}
}
}).$mount('#app');
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
第一種:使用@keyup事件
<input type="text" v-model="firstname" @keyup="getfullName">+<input type="text" v-model="lastname" @keyup="getfullName">=<input type="text" v-model="fullname">
<br>
<br>
第二種:使用watch
<input type="text" v-model="firstn">+<input type="text" v-model="lastn">= <input type="text" v-model="fulln">
</div>
<script type="text/javascript">
const vm = new Vue({
data:{
firstname:'',
lastname:'',
fullname:'',
firstn:'',
lastn:'',
fulln:''
},
methods:{
getfullName() {
this.fullname = this.firstname +'-'+this.lastname;
}
},
watch:{
firstn(newVal,oldVal) {
this.fulln = newVal +'-'+this.lastn;
},
lastn(newVal,oldVal) {
this.fulln = this.firstn +'-'+newVal;
}
}
}).$mount('#app');
</script>
</body>
</html>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者