watch偵聽器作用
定義一個(gè)對(duì)象來(lái)創(chuàng)建監(jiān)聽器。這個(gè)對(duì)象包含要監(jiān)聽的數(shù)據(jù)屬性名稱及其對(duì)應(yīng)的回調(diào)函數(shù)。通過監(jiān)聽器來(lái)監(jiān)聽對(duì)象,來(lái)實(shí)現(xiàn)數(shù)據(jù)的前后變化的強(qiáng)制同步。
基礎(chǔ)用法
- 方式1
<template>
<div class="test">
姓名:<el-input v-model="userName" style="width:30%;" size="medium"></el-input>
</div>
</template>
<script>
export default {
components: {},
name: "test",
data() {
return {
userName: "張三",
};
},
watch: {
userName(newVal, oldVal) {
console.log("newVal = " + newVal);
console.log("oldVal = " + oldVal);
}
},
mounted() {},
beforeCreate() {},
created() {},
methods: {},
};
</script>
<style scoped></style>

- 方式2
watch: {
userName : {
handler(newVal, oldVal) {
console.log("newVal = " + newVal);
console.log("oldVal = " + oldVal);
}
}
},
immediate用法
- immediate屬性為true時(shí),一直都會(huì)監(jiān)聽。
- immediate屬性為false時(shí),默認(rèn)用法,值發(fā)生改變才監(jiān)聽。
<template>
<div class="test">
姓名:<el-input v-model="userName" style="width:30%;" size="medium"></el-input>
</div>
</template>
<script>
export default {
components: {},
name: "test",
data() {
return {
userName: "張三",
};
},
watch: {
userName : {
handler(newVal, oldVal) {
console.log("newVal = " + newVal);
console.log("oldVal = " + oldVal);
},
immediate: true
}
},
mounted() {},
beforeCreate() {},
created() {},
methods: {},
};
</script>
<style scoped></style>

監(jiān)聽對(duì)象和數(shù)組情況
監(jiān)聽對(duì)象
- deep屬性值為true時(shí),監(jiān)聽對(duì)象整個(gè)內(nèi)部的屬性;
- deep屬性值為false時(shí),則監(jiān)聽不到對(duì)象整個(gè)內(nèi)部的屬性。
<template>
<div class="test">
地址:<el-input v-model="tempUserObj.info.address" style="width:30%;" size="medium"></el-input>
</div>
</template>
<script>
export default {
components: {},
name: "test",
data() {
return {
tempUserObj: {
"id" : "123456",
"family" : ["father", "sister", "brother"],
"info" : {
"age" : 30,
"address" : "吉林省長(zhǎng)春市朝陽(yáng)區(qū)"
},
},
};
},
watch: {
tempUserObj : {
handler(newVal, oldVal) {
console.log("newVal = " + JSON.stringify(newVal));
console.log("oldVal = " + JSON.stringify(oldVal));
},
immediate: true,
deep: true
}
},
mounted() {},
beforeCreate() {},
created() {},
methods: {},
};
</script>
<style scoped></style>

監(jiān)聽數(shù)組
watch: {
familyArr : {
handler(newVal, oldVal) {
console.log("newVal = " + JSON.stringify(newVal));
console.log("oldVal = " + JSON.stringify(oldVal));
},
deep: true
}
},