<template>
<div>
<h1>监视属性</h1>
</div>
<h2>天气案例</h2><hr/>
<div>
<h2>今天天气很{{info}} {{x}}</h2>
<!-- <button v-on:click="isHot =!isHot; x++" >切换天气</button> -->
<button v-on:click="changeWeather" >切换天气</button>
</div>
<hr/>
<h2>天气案例_监视属性</h2><hr/>
<h3>a的值是{{numbers.a}}</h3>
<button v-on:click="numbers.a++">点我让a+1</button><hr/>
<h3>b的值是{{numbers.b}}</h3>
<button v-on:click="numbers.b++">点我让b+1</button><hr/>
<button v-on:click="numbers = {a:666,b:888}">彻底替换对象改变ab</button><hr/>
监视属性watch:<hr/>
1.当被监视的属性变化时,回调函数自动调用,进行相关操作<hr/>
2.监视的属性必须存在,才能进行监视<hr/>
3.监视的两种写法:<hr/>
(1).new Vue时传入watch配置<hr/>
(2).通过vm.$watch监视<hr/>
深度监视:<hr/>
(1).Vue中的watch默认不检测对象内部值得改变(一层)。<hr/>
(2).配置deep:true可以检测对象内部值改变(多层)<hr/>
备注:<hr/>
(1).Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以!<hr/>
(2).使用watch时根据数据的具体结构,决定是否采用深度监视<hr/>
</template>
<script>
// import 01_初始Vue from './components.';
export default {
//data的第二种写法:函数式
data() {
// console.log('@@@',this);
return {
// 为真就是热 ,为假就是凉爽
isHot: true,
x:'1',
numbers:{
a:1,
b:1
}
}
},
methods:{
changeWeather () {
this.isHot =!this.isHot
}
},
computed:{
info () {
return this.isHot ? '炎热': '凉爽'
}
},
watch:{
'isHot':{
immediate:true,//初始化时让handler调用一下
//handler什么时候调用? 当isHot发生改变时。
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
},
},
// 简写
// isHot(newValue,oldValue){
// console.log('isHot被修改了',newValue,oldValue)
// }
// 计算属性的值也可以监听
// info:{
// immediate:true,//初始化时让handler调用一下
// //handler什么时候调用? 当isHot发生改变时。
// handler(newValue,oldValue){
// console.log('info被修改了',newValue,oldValue)
// },
// },
//监视多级结构中某个属性的变化
// 'numbers.a':{
// handler(){
// console.log('a被改变了')
// },
// },
//监视多个结构中所有属性的变化
numbers:{
deep:true,
handler(){
console.log('numbers改变了')
}
}
}
}
// this.$watch('ishot',{
// immediate:true,//初始化时让handler调用一下
// deep:true, //深度监视
// //handler什么时候调用? 当isHot发生改变时。
// handler(newValue,oldValue){
// console.log('info被修改了',newValue,oldValue)
// }
// })
// this.$watch('isHot',function(newValue,oldValue){
// console.log('isHot被修改了',newValue,oldValue)
// })
// 所有vue所管理的函数,都要写成普通函数,不要写成箭头函数
</script>
<style scoped>
</style>
09监视属性
最新推荐文章于 2024-07-08 10:04:44 发布