為什麼更新父元件的非props屬性,子元件 props watch 會觸發?

發表於2022-08-21

父元件

<template>
  <div>
    <Child
        :test="{ test }"
    >
    </Child>
    {{ anotherTest }}
  </div>
</template>

<script>
import Child from "@/components/Child"

export default {
  name: 'Father',
  components: {
    Child,
  },
  data() {
    return {
      test: {},
      anotherTest: '',
    }
  },
  watch: {
    test(newTest, oldTest) {
      console.log('Father test changed')
    }
  },
  created() {
    setTimeout(()=> this.anotherTest = '123', 1000)
  },

}
</script>

子元件

<template>
  <div>{{ test }}</div>
</template>

<script>

export default {
  name: "Child",
  props: {
    test: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    test(newTest, OldTest) {
      console.log('Child test changed')
      console.log(newTest)
      console.log(OldTest)
    }
  }
}
</script>

列印結果 Child test changed
這是什麼原因?

相關文章