Vue 深度监视

想要深度监视:需要在选项参数中指定 deep: true


示例

watch: {
    numbers: {
        // 配置 deep 可以监测对象内部值改变(多层)
        deep: true,
        handler(newValue, oldValue) {
            console.log('numbers 改变了')
        }
    }
}


实例

这里需要做到监听 numbers 对象中的 a 和 b 值的变化,

a 或 b 产生变化则在控制台打印 'numbers 改变了'

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>深度监视</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="root">
    <h2>a值:{{numbers.a}}</h2>
    <h2>b值:{{numbers.b}}</h2>
    <button @click="numbers.a++">a+1</button>
    <button @click="numbers.b++">b+1</button>
</div>
</body>
<script type="text/javascript">
    new Vue({
        el: '#root',
        data: {
            isHot: true,
            numbers: {
                a: 1,
                b: 1
            }
        },
        watch: {
            numbers: {
                // 配置 deep 可以监测对象内部值改变(多层)
                deep: true,
                handler(newValue, oldValue) {
                    console.log('numbers 改变了')
                }
            }
        }
    })
</script>
</html>

总结:

  • Vue 中的 watch 默认不监测对象内部值的改变(一层)
  • 在选项参数中指定 deep: true 可以监测对象内部值改变(多层)

备注:

  • Vue 自身可以监测对象内部值的改变,但 Vue 提供的 watch 默认不可以
  • 使用 watch 时根据数据的具体结构,决定是否采用深度监视
  • 默认不开启深度监测是为了效率


posted @ 2022-04-06 15:04  春暖花开鸟  阅读(208)  评论(0编辑  收藏  举报