VUE2 计算属性 computed及监视属性 watch

计算属性 computed

<span>{{fullName}}</span>
data: {
    firstName: '张',
    lastName: '三'
},
computed: {
    fullName: {
        // get有什么作用?当读取fullName时,get就会被调用,且返回值就作为fullName的值。
        // get什么时候被调用? 1.初次读取fullName时  2.所依赖的数据发生变化时
        get(){
            return this.firstName + this.lastName
            // return '李四'
        },
        // set什么时候被调用?当fullName被修改时
        set(){
            this.firstName = '李'
            this.lastName = '四'
         }
    }
}

计算属性的简写形式:

data: {
    firstName: '张',
    lastName: '三'
},
computed: {
    fullName() {     //这里的 fullName 是值,不是函数!!!
        return this.firstName + this.lastName   //将计算后的值返回给fullName
     }
}

监视属性 watch

<span>{{isHot ? '炎热':'寒冷'}}</span>

<button @click="onClick">切换天气</button>
data: {
    isHot: true
},
methods: {
    onClick(){
        this.isHot = !this.isHot
    }
},
// 监视属性可以监视data中的值,也可以监视计算属性中的值
watch: {
    isHot: {
        // immediate为true表示初始化时让handler调用一下

        immediate: true,
        // 深度监视,一般用于监视多层数据结构的时候用到,比如对象中某个数据的变化
        // deep: true,
        // handler什么时候调用?当isHot发生改变时,里面可以观察到旧值和新值的变化。
        handler(newValue, oldValue){
            console.log('被调用了', newValue, oldValue)
        }
     }
}

监视属性的简写形式:注意在不使用immediate、deep的时候可以使用简写形式

data: {
    isHot: true
},
methods: {
    onClick(){
        this.isHot = !this.isHot
    }
},
// 注意在不使用immediate、deep的时候可以使用简写形式
watch: {
    isHot(newValue, oldValue) {
           console.log('被调用了', newValue, oldValue)
        }
     }
}

监视属性的完整写法:

vm.$watch('isHot', {
    // immediate: true,
    // deep: true,
    handler(newValue, oldValue){
            console.log('被调用了', newValue, oldValue)
    }
})
//或者
vm.$watch('isHot', function(){
    // immediate: true,
    // deep: true,
    console.log('被调用了', newValue, oldValue)
})

应用案例:

watch:{
    '$route.query.id'(newValue, oldValue){
        console.log('变化', newValue, oldValue)
        location.reload()                       // 当路由中参数变化时,刷新当前页面
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

中亿丰数字科技集团有限公司

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值