VUE中钩子函数computed和watch

computed和watch的作用和区别

1.computed计算属性可以把在dom元素中计算的变到VM中计算,加快速度

2.侦听器watch 比computed灵活;可以做函数节流,Ajax异步数据获取,操作DOM;依赖固定的数据类型

3.总结 computed计算新属性,惰性求值,watch侦听一个原本就存在的数据,发生变化就执行函数

computed适合一个数据被多个数据影响,由多个数据计算得来

watch使用多个数据影响一个数据

watch不能双向绑定
(使用了钩子函数computed和watch,split(’.’),v-model)

<template>
    <div>
        <label><input type="text" placeholder="输入姓" v-model="firstName"> </input></label><br>
        <label><input type="text" placeholder="输入名" v-model="lastName"> </input></label>
        <p>------------------单向绑定-------------------------</p>
        <label>姓名 <input type="text" placeholder="输入姓名" v-model="fullNameOne"> </input></label>
        <p>------------------双向绑定-------------------------</p>
        <label>姓名 <input type="text" placeholder="输入姓名" v-model="fullNameTwo"> </input></label>
        <p>------------------单向绑定-------------------------</p>
        <label>姓名 <input type="text" placeholder="输入姓名" v-model="fullNameThree"> </input></label>
    </div>
</template>

<script>
    export default {
        name: "ComputedAndWatch",
        data(){
            return{
                firstName:'',
                lastName:'',
                fullNameThree:'',
            }
        },
        computed:{
            fullNameOne:{
                get(){
                    return this.firstName+'.'+this.lastName;
                }
            },
            fullNameTwo:{
                get(){
                    return this.firstName+'.'+this.lastName;
                },
                set(value){
                    let names = value.split('.');
                    this.firstName = names[0];
                    this.lastName = names[1];
                }
            }
        },
        watch:{
            //watch监听属性,监听firstName和lastName属性发生变法,执行的方法,方法名称就是该属性名称
            firstName(value){
                console.log(`姓发生了变化${value}`);
                this.fullNameThree = value + this.lastName;
            },
            lastName(value){
                console.log(`姓发生了变化${value}`);
                this.fullNameThree = this.firstName + value;
            }
        }
    }
</script>

<style scoped>

</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值