這篇文章給大家介紹怎么在Vue中使用watch方法監(jiān)聽數(shù)據(jù),內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

景泰網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),景泰網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為景泰成百上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢,請找那個(gè)售后服務(wù)好的景泰做網(wǎng)站的公司定做!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>監(jiān)聽方法watch的使用</title>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>
<body>
<div id="root"></div>
<script>
var vm = new Vue({
el: "#root",
data: { obj: {name: "zhaoolee", age: 12} , tel:6666666},
template: `<div><div>姓名: {{obj.name}}</div>
<div>電話: {{tel}}</div>
<input type="text" v-model="obj.name">
<input type="text" v-model="tel"></div>`,
watch: {
obj: {
handler(){
console.log("obj被改變");
},
// 頁面加載之初先執(zhí)行一次handle
immediate: true,
// 深度檢查屬性,即使對象內(nèi)部的屬性值改變, 也能檢測到(比較消耗性能)
deep: true
},
"obj.name": {
handler(){
console.log("=>obj.name被改變");
}
},
tel:{
handler(){
console.log("tel被改變");
}
}
}
})
</script>
</body>
</html>對應(yīng)一個(gè)對象,鍵是觀察表達(dá)式,值是對應(yīng)回調(diào)。值也可以是方法名,或者是對象,包含選項(xiàng)。在實(shí)例化時(shí)為每個(gè)鍵調(diào)用 $watch() ;
//使用官方vue-cli腳手架書寫
<template>
//觀察數(shù)據(jù)為字符串或數(shù)組
<input v-model="example0"/>
<input v-model="example1"/>
/當(dāng)單觀察數(shù)據(jù)examples2為對象時(shí),如果鍵值發(fā)生變化,為了監(jiān)聽到數(shù)據(jù)變化,需要添加deep:true參數(shù)
<input v-model="example2.inner0"/>
</template>
<script>
export default {
data(){
return {
example0:"",
example1:"",
example2:{
inner0:1,
innner1:2
}
}
},
watch:{
example0(curVal,oldVal){
console.log(curVal,oldVal);
},
example1:'a',//值可以為methods的方法名
example2:{
//注意:當(dāng)觀察的數(shù)據(jù)為對象或數(shù)組時(shí),curVal和oldVal是相等的,因?yàn)檫@兩個(gè)形參指向的是同一個(gè)數(shù)據(jù)對象
handler(curVal,oldVal){
conosle.log(curVal,oldVal)
},
deep:true
}
},
methods:{
a(curVal,oldVal){
conosle.log(curVal,oldVal)
}
}
}
</script>關(guān)于怎么在Vue中使用watch方法監(jiān)聽數(shù)據(jù)就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
網(wǎng)站名稱:怎么在Vue中使用watch方法監(jiān)聽數(shù)據(jù)
路徑分享:http://chinadenli.net/article6/ppcjig.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動(dòng)態(tài)網(wǎng)站、品牌網(wǎng)站建設(shè)、網(wǎng)站制作、面包屑導(dǎo)航、品牌網(wǎng)站制作、App設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)