Vue3.0中watch的使用方法

242 阅读1分钟

监听 reactive 内部数据

注意 1:监听 reactive 内部数据时,强制开启了深度监听,且配置无效;监听对象的时候 newValue 和 oldValue 是全等的。

<template>
  <p>{{ obj.hobby.eat }}</p>
  <button @click="obj.hobby.eat = '面条'">click</button>
</template>

<script>
  import { watch, reactive } from 'vue'
  export default {
    name: 'App',
    setup() {
      const obj = reactive({
        name: 'ifer',
        hobby: {
          eat: '西瓜'
        }
      })
      watch(obj, (newValue, oldValue) => {
        // 注意1:监听对象的时候,新旧值是相等的
        // 注意2:强制开启深度监听,配置无效
        console.log(newValue === oldValue) // true
      })

      return { obj }
    }
  }
</script>

注意 2:reactive 的【内部对象】也是一个 reactive 类型的数据。

<template>
  <p>{{ obj.hobby.eat }}</p>
  <button @click="obj.hobby.eat = '面条'">click</button>
</template>

<script>
import { watch, reactive, isReactive } from 'vue'
export default {
  name: 'App',
  setup() {
    const obj = reactive({
      name: 'ifer',
      hobby: {
        eat: '西瓜',
      },
    })
    // reactive 的【内部对象】也是一个 reactive 类型的数据
    // console.log(isReactive(obj.hobby))
    watch(obj.hobby, (newValue, oldValue) => {
      console.log(newValue === oldValue) // true
    })

    return { obj }
  },
}
</script>

注意 3:对 reactive 自身的修改则不会触发监听。

<template>
  <p>{{ obj.hobby.eat }}</p>
  <button @click="obj.hobby = { eat: '面条' }">click</button>
</template>

<script>
import { watch, reactive } from 'vue'
export default {
  name: 'App',
  setup() {
    const obj = reactive({
      name: 'ifer',
      hobby: {
        eat: '西瓜',
      },
    })
    watch(obj.hobby, (newValue, oldValue) => {
      // obj.hobby = { eat: '面条' }
      console.log('对 reactive 自身的修改不会触发监听')
    })
    return { obj }
  },
}
</script>