一、简单标准的用法
watch最简单的用法
watch: {
weather(newValue, oldValue){
console.log("简写版的weather的值改变了", newValue, oldValue);
}
}
完整代码
<!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>Document</title>
</head>
<script type="text/javascript" src="vue.js"></script>
<body>
<div id="root">
<h2>今天的天气是:{{name}}</h2>
<button @click="change">点击切换</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false;
var root = new Vue({
el: '#root',
data: { weather: true },
computed: {
name() {
return this.weather ? "晴天" : "下雨";
}
},
methods: {
change() {
this.weather = !this.weather
}
},
watch: {
weather: {
immediate:true, // 初始化时让handler调用一下
handler(newValue,oldValue){
// newValue:改变后的新值
// oldValue:改变前的旧值
console.log("weather天气改变了",newValue,oldValue);
}
}
},
})
</script>
</body>
</html>
二、在root(Vue)结构之外调用watch用法
<!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>Document</title>
</head>
<script type="text/javascript" src="vue.js"></script>
<body>
<div id="root">
<h2>今天的天气是:{{name}}</h2>
<button @click="change">点击切换</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false;
var root = new Vue({
el: '#root',
data: { weather: true },
computed: {
name() {
return this.weather ? "晴天" : "下雨";
}
},
methods: {
change() {
this.weather = !this.weather
}
},
})
// 在root(Vue)结构之外调用watch
root.$watch('weather', {
immediate:true, // 初始化时让handler调用一下
handler(newValue,oldValue){
// newValue:改变后的新值
// oldValue:改变前的旧值
console.log("weather天气改变了",newValue,oldValue);
}
}
)
</script>
</body>
</html>
三、对DATA数组中的具体值的深度监视实例
<!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>Document</title>
</head>
<script type="text/javascript" src="vue.js"></script>
<body>
<div id="root">
<h2>今天的天气是:{{name}}</h2>
<button @click="change">点击切换</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false;
var root = new Vue({
el: '#root',
data: {
weather: true,
numbers: { a: "1", b: "2" }
},
computed: {
name() {
return this.weather ? "晴天" : "下雨";
}
},
methods: {
change() {
this.numbers.a = "8";
this.weather = !this.weather;
}
},
watch: {
'numbers.a':{
immediate: true, // 初始化时让handler调用一下
handler(newValue, oldValue) {
// deep:true,// 深度监视
// newValue:改变后的新值
// oldValue:改变前的旧值
console.log("a的值改变了", newValue, oldValue);
}
}
}
})
</script>
</body>
</html>