1.基础监听(监听一个字段)
<template>
<h1>{{userName }}</h1>
<input type="text" v-model="userName" />
</template>
<script>
export default {
name: "Watch",
data() {
return {
userName: "ll"
};
},
watch:{
userName(newVal,oldVal){
console.log(newVal,oldVal);
},
},
methods: {},
};
</script>
<style scoped>
</style>
2.刚一进页面就监听(immediate)
<template>
<h1>{{userName }}</h1>
<input type="text" v-model="userName" />
</template>
<script>
export default {
name: "Watch",
data() {
return {
userName: "ll"
};
},
watch:{
userName:{
handler(newVal,oldVal){
console.log(newVal,oldVal);
},
immediate:true
},
methods: {},
};
</script>
<style scoped>
</style>
3.如果监听对象(deep)
<template>
<h1>{{ obj.userName }}</h1>
<input type="text" v-model="obj.userName" />
</template>
<script>
export default {
name: "Watch",
data() {
return {
obj: {
userName: "ll",
age:20
},
};
},
watch: {
obj: {
handler(newVal, oldVal) {
console.log(newVal, oldVal);
},
deep: true,
immediate: true,
},
},
methods: {},
};
</script>
<style scoped>
</style>
4.只监听对象中的某一项
<template>
<h1>{{ obj.userName }}</h1>
<input type="text" v-model="obj.userName" />
</template>
<script>
export default {
name: "Watch",
data() {
return {
obj: {
userName: "ll",
age:20
},
};
},
watch: {
'obj.userName': {
handler(newVal, oldVal) {
console.log(newVal, oldVal);
},
immediate: true,
},
},
methods: {},
};
</script>
<style scoped>
</style>