VUE3 watch

193 阅读1分钟

使用步骤

  1. 从vue框架中导入watch函数

  2. 在setup函数中执行watch函数开启对响应式数据的监听

  3. watch函数接收三个常规参数

    3.1. 第一个参数为函数,返回你要监听变化的响应式数据

    3.2. 第二个参数为响应式数据变化之后要执行的回调函数

    3.3. 第三个参数为一个对象,在里面配置是否开启立刻执行或者深度监听

 <template>
  {{ name }}
  {{ info.age }}
  <button @click="name = 'pink'">change name</button>
  <button @click="info.age++">change age</button>
</template>

<script>
import { reactive, toRefs, watch } from 'vue'
export default {
  setup() {
    const state = reactive({
      name: 'cp',
      info: {
        age: 18
      }
    })
    watch(() => {
      // 详细的告知你要监听谁
      return state.info.age
    }, () => {
      // 数据变化之后的回调函数
      console.log('age发生了变化')
    })
    return {
      ...toRefs(state)
    }
  }
}
</script>