0%

监视属性(watch)

<div id="root">
        <h2>今天天气很{{info}}</h2>
        <button @click="changeWeather">点我切换天气</button>
</div>
    <script type="text/javascript">
        Vue.config.productionTip = false;
        const vm = new Vue({
            el: '#root',
            data: {
                isHot: true
            },
            //计算属性
            computed: {
                info() {
                    return this.isHot ? '炎热' : '凉爽'
                }
            },
            //方法
            methods: {
                changeWeather() {
                    this.isHot = !this.isHot;
                }
            },
            //监视
            watch: {
                isHot: {
                    //Vue中的watch默认不可以监视多级结构中的属性
                    //开启deep: true深度监视后就可以监测多级结构中某个属性发生变化
                    deep: true,
  
                    //初始化时让handler调用一下
                    immediate: true,
                    
                    //当isHot发生改变时handler函数被调用,并返回新值和旧值
                    handler(newValue, oldValue) {
                        console.log(newValue, oldValue);
                    }
                }
            },
        })
        //另一种写法
        // vm.$watch('isHot', {
        //     immediate: true,
        //     //当isHot发生改变时handler函数被调用
        //     handler(newValue, oldValue) {
        //         console.log();
        //     }
        // })
    </script>
//当监视属性中确定不使用deep和immediate时,就可以使用简写
                isHot(newValue, oldValue) {
                    console.log("isHot被修改了", newValue, oldValue);
                }