监督属性

发布时间 2023-12-28 17:20:46作者: 郭培鑫同学

监督属性


何为监督属性:这是vue一个配置属性,主要是监督已有的属性值。

案例:实现监督天气变化,在控制台输出变化。


<body>
    <!-- 定义一个vue容器 -->
    <div id="root">
        <h3>广东天气很{{info}}</h3>
        <button @click="reverseWeather">切换天气</button>
    </div>
    <script>
        const vm = new Vue({
            el: '#root',
            data: {
                isHot:true
            },
            computed:{
                info(){
                    return this.isHot?'炎热':'寒冷'
                }
            },
            methods: {
                reverseWeather(){
                    this.isHot = !this.isHot
                }
            },
            // 第一种:使用配置属性  
            watch:{
                isHot:{
                    handler(newValue,oldValue){
                        console.log('isHot被修改',newValue,oldValue)
                    }
                },
                // info:{
                //     handler(newValue,oldValue){
                //         console.log('info被修改',newValue,oldValue)
                //     }
                // }
            }
        })
        // 第二种:使用api
        vm.$watch('info',{
            handler(newValue,oldValue){
                console.log('info被修改',newValue,oldValue)
            }
        })
    </script>
</body>

vue代码解释:首先天气info有两种:炎热和寒冷,data配置项使用isHot布尔值,用computer配置项实现逻辑判断;其次给按钮绑定点击事件,在methods配置项中实现反转天气;最后watch配置项用于在控制台输出每次变换前和变换后的天气;主要使用两种方式实现监督。