Vue3 watch 侦听器的使用

watch 使用的方法与vue2大致相同,主要是vue3的写法

<script setup lang="ts">
import { ref, watch } from 'vue'
// 简单的侦听一个属性的值
const message = ref()
watch(message, (nn) => {
  console.log(nn)
})
// 侦听源 以函数的方式返回参数,作为回调函数的入参
const x = ref(0)
watch(
  () => x.value,
  (sum) => {
    console.log(sum)
  }
)
// 侦听一个对象
const obj = ref({ count: 1 })
// watch(obj.count, () => {}) // 这种是错误的
watch(
  // 正确
  () => obj.value.count,
  (count) => {
    console.log(count)
  }
)
// deep: true 深度侦听
const state = ref({ someObject: 111 })
// watch(
//   () => state.someObject,
//   (newValue, oldValue) => {},
//   { deep: true }
// )
// immediate: true 立刻执行
const source = ref('')
watch(source, (newValue, oldValue) => {}, { immediate: true })
</script>

<template>
  <main>
    <input type="text" v-model="message" />
    <button @click="x++">click</button>
    <button @click="obj.count++">click</button>
  </main>
</template>

watch vue3官网

posted @ 2023-03-15 17:23  LC蜗牛  阅读(42)  评论(0编辑  收藏  举报