vue3.x教程-watch监视器的使用5-监视多个数据

介绍

监视多个无关系的数据,值发生变化时,执行函数

例子

如下图,监视 name、对象中的 score属性:

HTML代码:

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

TS代码:

<script lang="ts" setup name='Student'>
    // 导入 watch
    import { ref,reactive,watch } from 'vue'
    let name = ref('李雷')
    // 对象
    let student = reactive({
        age:'',
        password:'',
        score:{
            shuxue:'80',
            yuwen:'70',
        }
    })
    // 监视器,只监视name、对象中的score属性
    watch(
        [
            name,
            // score属性是对象属性,必须定义函数返回该属性,否则赋值新对象,监视不到
            ()=>student.score,
        ],
        (newValue,oldValue)=>{
            console.log("新值:",newValue)
            console.log("原值:",oldValue)
        },
        {
            // 不开启深度监视,给score赋新对象时才能监听到
            // 开启深度监视,修改score中的属性值,也能够监听到
            deep:true
        }
    )
    // 给student的score属性赋新对象
    function modify(){
        student.score = {
            shuxue:'10',
            yuwen:'20',
        }
    }
</script>

特点

同时监视 name、student.score 的值变化,值发生改变时,执行监视函数


原文出处:/show_1GW3ghEd6N2e.html