vue3.x教程-watch监听器的使用3-监视 reactive对象类型

介绍

监视 reactive对象类型,默认开启深度监视

例子

html代码:

<template>
    年龄: <input type="text" v-model="student.age" />
    <br>
    密码: <input type="text" v-model="student.password" />
    <br>
    <button @click="modify">给student赋新值</button>
</template>

ts代码:

<script lang="ts" setup name='Student'>
    // 导入 watch
    import { reactive,watch } from 'vue'
    // 年龄
    let student = reactive({
        age:'',
        password:'',
    })
    watch(student,(newValue,oldValue)=>{
        console.log("新值:",newValue)
        console.log("原值:",oldValue)

    })
    // 给student赋新对象
    function modify(){
        Object.assign(
            student,
            {
                age:'20',
                password:'123456'
            },
        )
    }
</script>

特点

  • 默认开启深度监视
  • 对象中,任意一个属性发生变化,都会监视到

注意:修改属性后,新值、原值是一样的

如上图,修改年龄后,新值、原值是一样的,这是因为修改的是 student 对象的 age 属性,即:修改的是 同一个对象,所以新值、原值是同一个值

执行下面代码:

Object.assign(
    student,
    {
        age:'20',
        password:'123456'
    },
)

是将 大括号对象的age、password属性值 赋给 student 对象的 age、password,即:修改的是 同一个对象,所以 newValue、oldValue 也是相同的


原文出处:/show_1GW3ggbGuAPz.html