觀察一個(gè)Vue實(shí)例的變化,當(dāng)這個(gè)實(shí)例發(fā)生變化的時(shí)候就執(zhí)行function里面的語句
HTML代碼:
<div id="watch">
firstName:<input type="text" name="li" v-model="firstName">
<br>
lastName:<input type="text" name="fei" v-model="lastName">
<p>fullName: {{fullName}}</p>
</div>
JS代碼:
var vm = new Vue({
el: '#watch',
data: {
firstName: 'a',
lastName: 'fei',
fullName: 'a fei'
},
watch: {
firstName: function (val) {
this.fullName = val + ' ' + this.lastName
},
lastName: function (val) {
this.fullName = this.firstName + ' ' + val
}
}
})
在這個(gè)代碼中,用watch方法監(jiān)聽了 firstName和lastName這兩個(gè)變量,在input輸入框做了雙向綁定,當(dāng)firstName的值發(fā)生改變的時(shí)候,firstName變量也同樣會(huì)改變;lastName同理.因?yàn)閣atch觀察到數(shù)據(jù)的改變,watch里的方法就會(huì)運(yùn)行,fullName的值也會(huì)發(fā)生相應(yīng)的改變