监视属性watch

1.当被监视的属性变化时,回调函数自动调用,进行相关操作
2.监视的属性必须存在,才能进行监视
3.自定义属性和计算属性都可以被监听
深度监视:
(1)vue中的watch默认不检测对象内部值的变化(一层)
(2)配置deep:true可以检测对象内部值的改变(二层)
备注:
(1)vue自身可以检测内部值的改变,但vue提供的watch默认不可以
(2)使用watch时根据数据的具体结构,决定是否采用深度检测

<template>
    <div>
        <div>当前求和:{{sum}}</div>
        <button @click="sum++">点击+1</button>
    </div>
</template>
<script>
import { watch,ref, reactive } from 'vue'
export default {
    setup(){
        let sum=ref(0)
        let msg=ref('你好,李焕英')
        let person=reactive({
            name:'章三',
            age:18,
            job:{
                j1:{
                    salary:'20K'
                }
            }
        })
        //情况一:监听ref所定义的一个响应式数据
        watch(sum,(oldValue,newValue)=>{
            console.log('监听到了改变',oldValue,newValue);
        })
        //情况二:监听ref所定义的多个响应式数据
        watch([sum,msg],(newValue,oldValue)=>{
            console.log('sum or msg 变化了',newValue,oldValue);
        })
        //情况三:监听reactive所定义的一个响应式数据,注意,此处无法正确的展示旧value
        watch(person.value,(newValue,oldValue)=>{
            console.log('person变化了',newValue,oldValue);
        })
        //情况四:监听reactive所定义的一个响应式数据中的某个属性
        watch(()=>person.name,(newValue,oldValue)=>{
            console.log('person的name变化了',newValue,oldValue);
        })
        //情况五:监听reactive所定义的一个响应式数据中的某些属性
        watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{
            console.log('person的name和age变化了',newValue,oldValue);
        })
        return {
            sum,
            msg,
            person
        }
    }
}
</script>

用监视属性完成计算属性的案例->名字拼接

<template>
    <div>
        <h1>一个人的信息</h1>
        姓:<input type="text" v-model="firstName" />
        <br>
        名:<input type="text" v-model="lastName" />
        <br>
        全名:<span>{{fullName}}</span>
        <br>
        修改:<input type="text" v-model="fullName" />
    </div>
</template>
<script setup>
import { watch,ref} from 'vue'
    let firstName=ref('张')
    let lastName=ref('三')
    let fullName=ref('张-三')
    watch(firstName,(newValue,oldValue)=>{
        setTimeout(()=>{
        fullName.value=newValue+'-'+lastName.value
        },1000)

    })
    watch(lastName,(newValue,oldValue)=>{
        fullName.value=firstName.value+'-'+newValue

    })
</script>

computed和watch之间的区别:
1.computed能完成的功能,watch都可以完成
2.watch能完成的功能,computed不一定能完成,例如:watch可以进行异步操作
vue2中两个有关this重要的小原则
1.所有被vue管理的函数,最好写成普通函数,这样this的指向才是vm或组件实例对象
2.所有不被vue所管理的函数(定时器的回调、ajax的回调函数,promise回调函数等),最好写成箭头函数,这样this的指向才是vm或组件实例对象

 

posted @ 2022-12-02 15:08  终究还是避免不了遗憾  阅读(45)  评论(0编辑  收藏  举报