<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>watch的使用</title>
<script src="https://cdn.staticfile.org/vue/3.0.5/vue.global.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="username">
<input type="text" v-model="age">
<h3>{{sum}}</h3>
<button @click="changeTestA">a++</button>
<button @click="changeTestB">b++</button>
</div>
</body>
<script>
const app = {
// el: "#app",
data() {
return {
username: "菜菜",
age: 18,
sum: "",
test: {
a: 1,
b: 1
}
}
},
methods: {
changeTestA() {
this.test.a++;
},
changeTestB() {
this.test.a++;
}
},
watch: {
username: {
immediate: true,
handler(newValue, oldValue) {
this.sum = "我是" + this.username + ",年龄" + this.age;
console.log("username旧值" + oldValue + ";usenamex新值" + newValue)
}
},
age: {
immediate: true,
handler() {
this.sum = "我是" + this.username + ",年龄" + this.age;
}
},
test: {
immediate: true,
deep: true, //默认是false 不会对test进行深层次监听 设为true后可以进行深层次监听
handler() {
console.log("test改变");
}
},
//不需要设置其他属性时可直接使用简写 如下:
// test() { //只有test改变时才会触发(不包含内部层次)
// console.log("test改变");
// }
}
};
const vm = Vue.createApp(app);
vm.mount("#app");
//watch的第二种写法
//vm.$watch('prop',function(o,n){})
</script>
</html>