Skip to content

关于vue中watch检测到不到对象属性的变化 #124

@isaaxite

Description

@isaaxite
Owner

前言

在vue开发的过程中发现一个问题:改变vue.$data中对象的属性,watch是观测不到变化,但其实对象的属性是有变化的。这……,有点难以置信!

正文

<template>
  <div>
    <dl>name: {{option.name}}</dl>
    <dl>age: {{option.age}}</dl>
    <dl>
      <button @click="updateAgeTo25">update age with 25</button>
    </dl>
  </div>
</template>

<script>
export default {
  data () {
    return {
      option: {
        name: "isaac",
        age: 24
      }
    }
  },
  watch: {
    option(val) {
      console.log(val)
    }
  },
  methods: {
    updateAgeTo25() {
      this.option.age = 25
    }
  }
}
</script>

image

image

如结果所示,option.age已经更新,但是watch中的option函数并没有被触发。

vue的watch钩子会那么鸡肋?我是不信的了。

深层watch

  ...
  watch: {
    option: {
      handler(newVal) {
        console.log(newVal);
      },
      deep: true,
      immediate: true
    }
  },
  ...

需要深层watch就需要开启deep属性

image

image

如结果所示。

另外,你会发现,在age没有变化前也是有打印出option,这是因为开启immediate属性,设定为true

该回调将会在侦听开始之后被立即调用

[来自vue文档的说明]

Activity

changed the title [-]vue中watch并不能检测到对象属性的变化[/-] [+]关于vue中watch检测到不到对象属性的变化[/+] on Jan 28, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @isaaxite

        Issue actions

          关于vue中watch检测到不到对象属性的变化 · Issue #124 · isaaxite/blog