Vue.js框架学习—侦听属性

在这里插入图片描述

一、侦听属性watch

  1. 当被侦听的属性变化时,回调函数自动调用,进行相关操作。

  2. 监视的属性必须存在,才能进行监视。

  3. 监视的两种写法:

    • (1).new Vue时传入watch配置
    • (2).通过vm.$watch监视

二、侦听属性的效果

在这里插入图片描述

当点击页面中的button按钮时,调用methods方法中的函数,修改属性中的isHot的值,watch会侦听到isHot发生了变化,从而调用handler函数在控制台打印输出。

三、侦听属性的两种写法

1、Vue实例化时传入watch配置

<body>
    <div id="root">
        <span>今天的天气很{{info}}</span><br><br>
        <button @click="changeWeather">点击切换天气</button>
    </div>
</body>
<script>
    new Vue({
        el:'#root',
        data:{
            isHot:'true'
        },
        computed:{
            info(){
                return this.isHot? '炎热' : '凉爽'
            }
        },
        methods: {
            changeWeather(){
                this.isHot=!this.isHot
            }
        },
        watch:{
            isHot:{
                handler(oldValue,newValue){
                    console.log('isHot属性修改了',oldValue,newValue)
                }
            }
        }
    })
</script>

2、通过vm.$watch

<body>
    <div id="root">
        <span>今天的天气很{{info}}</span><br><br>
        <button @click="changeWeather">点击切换天气</button>
    </div>
</body>
<script>
    const vm=new Vue({
        el:'#root',
        data:{
            isHot:'true'
        },
        computed:{
            info(){
                return this.isHot? '炎热' : '凉爽'
            }
        },
        methods: {
            changeWeather(){
                this.isHot=!this.isHot
            }
        },
    })
    vm.$watch('isHot',{
        handler(oldValue,newValue){
            console.log('isHot属性修改了',oldValue,newValue)
        }
    })
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值