欢迎光临殡葬网
详情描述

1. 使用返回的停止函数(Vue 3)

// Composition API
import { watch, ref } from 'vue'

const count = ref(0)

// watch返回一个停止函数
const stopWatch = watch(count, (newVal, oldVal) => {
  console.log('count变化:', oldVal, '->', newVal)
})

// 调用停止函数取消监听
stopWatch()

2. 组件卸载时自动取消(Vue 3)

// 在setup中使用,组件卸载时会自动停止
import { watch, ref, onUnmounted } from 'vue'

export default {
  setup() {
    const count = ref(0)

    const stopWatch = watch(count, (newVal) => {
      console.log('count:', newVal)
    })

    // 也可以手动在组件卸载时停止
    onUnmounted(() => {
      stopWatch()
    })

    return { count }
  }
}

3. 使用条件控制(Vue 2/3通用)

// 通过条件判断控制是否执行
const count = ref(0)
const isWatching = ref(true)

watch(
  count,
  (newVal) => {
    if (!isWatching.value) return
    console.log('count:', newVal)
  }
)

// 取消监听
isWatching.value = false

4. Options API中的watch(Vue 2)

// Vue 2 Options API
export default {
  data() {
    return {
      count: 0
    }
  },

  watch: {
    count(newVal, oldVal) {
      console.log('count变化:', oldVal, '->', newVal)
    }
  },

  // 无法直接取消,但可以通过条件控制
  watch: {
    count: {
      handler(newVal, oldVal) {
        if (!this.isWatching) return
        console.log('count变化:', oldVal, '->', newVal)
      },
      immediate: true
    }
  },

  data() {
    return {
      isWatching: true
    }
  },

  methods: {
    stopWatching() {
      this.isWatching = false
    },
    startWatching() {
      this.isWatching = true
    }
  }
}

5. 使用$watch返回的停止函数(Vue 2)

// Vue 2 Options API
export default {
  data() {
    return {
      count: 0
    }
  },

  mounted() {
    // $watch返回取消函数
    this.unwatchCount = this.$watch(
      'count',
      (newVal, oldVal) => {
        console.log('count变化:', oldVal, '->', newVal)
      }
    )
  },

  beforeDestroy() {
    // 取消监听
    if (this.unwatchCount) {
      this.unwatchCount()
    }
  },

  methods: {
    stopWatching() {
      this.unwatchCount()
    }
  }
}

6. 监听多个数据源

import { watch, ref } from 'vue'

const count = ref(0)
const name = ref('')

// 监听多个数据源
const stopWatch1 = watch(count, handler)
const stopWatch2 = watch(name, handler)

// 批量取消
function stopAllWatches() {
  stopWatch1()
  stopWatch2()
}

7. 实用的封装示例

// watchManager.js
import { watch, ref, onUnmounted } from 'vue'

export function useWatchManager() {
  const watchers = []

  const watchAndTrack = (source, callback, options) => {
    const stop = watch(source, callback, options)
    watchers.push(stop)
    return stop
  }

  const stopAll = () => {
    watchers.forEach(stop => stop())
    watchers.length = 0
  }

  onUnmounted(stopAll)

  return {
    watch: watchAndTrack,
    stopAll,
    watchers
  }
}

// 使用示例
export default {
  setup() {
    const { watch: customWatch, stopAll } = useWatchManager()
    const count = ref(0)
    const name = ref('')

    customWatch(count, (val) => console.log('count:', val))
    customWatch(name, (val) => console.log('name:', val))

    // 一键取消所有监听
    const cancelAll = () => {
      stopAll()
    }

    return { count, name, cancelAll }
  }
}

最佳实践建议:

推荐使用Composition API的返回函数方式,代码更清晰 在组件卸载时务必清理watch,避免内存泄漏 对于复杂的监听逻辑,可以使用管理类统一管理 根据实际场景选择合适的取消方式
相关帖子
在异地去世的情况下,如何了解和申请运用现地的惠民殡葬政策?
在异地去世的情况下,如何了解和申请运用现地的惠民殡葬政策?
2026年各地共有产权住房政策有何差异,哪些城市更容易申请?
2026年各地共有产权住房政策有何差异,哪些城市更容易申请?
当长时间的情绪低落和紧张感影响日常生活时,可以尝试哪些自我调节方法?
当长时间的情绪低落和紧张感影响日常生活时,可以尝试哪些自我调节方法?
襄阳市殡葬服务正规公司-丧事摄像服务,1小时上门
襄阳市殡葬服务正规公司-丧事摄像服务,1小时上门
人在外地工作或学习,如何跨省异地补办居民身份证
人在外地工作或学习,如何跨省异地补办居民身份证
反季节购买家电和电子产品,需要注意哪些潜在的消费风险与问题?
反季节购买家电和电子产品,需要注意哪些潜在的消费风险与问题?
2026年个税汇算清缴,新增了哪些可以税前扣除的项目?
2026年个税汇算清缴,新增了哪些可以税前扣除的项目?
拉萨市丧事服务-入殓化妆,安全快捷
拉萨市丧事服务-入殓化妆,安全快捷
2026年常见误区澄清:外嫁女不能继承的是宅基地本身还是使用权?
2026年常见误区澄清:外嫁女不能继承的是宅基地本身还是使用权?
个人养老金账户与基本养老保险、企业年金在税收优惠上有何不同之处?
个人养老金账户与基本养老保险、企业年金在税收优惠上有何不同之处?
安庆市殡葬一条龙-丧礼录像,24小时服务热线
安庆市殡葬一条龙-丧礼录像,24小时服务热线
太原市殡葬服务公司一站式办理-白事追悼会策划,24小时服务热线
太原市殡葬服务公司一站式办理-白事追悼会策划,24小时服务热线
在人工智能普及的背景下,专业技术人才如何保持自身不可替代性?
在人工智能普及的背景下,专业技术人才如何保持自身不可替代性?
2026年,远程医疗与线上健康管理服务能否帮助降低部分医疗开支?
2026年,远程医疗与线上健康管理服务能否帮助降低部分医疗开支?
竞业限制协议中约定的违约金数额,法律上是否存在一个合理的上限标准?
竞业限制协议中约定的违约金数额,法律上是否存在一个合理的上限标准?
常德市殡葬服务|白事丧事一条龙,冰棺出租服务
常德市殡葬服务|白事丧事一条龙,冰棺出租服务
在等待救护车时,对晕倒者进行哪些观察可以为医护人员提供关键信息?
在等待救护车时,对晕倒者进行哪些观察可以为医护人员提供关键信息?
合肥市殡葬服务热线-丧葬摄像,全城服务
合肥市殡葬服务热线-丧葬摄像,全城服务
海西殡葬服务公司|白事一条龙办理,白事布置
海西殡葬服务公司|白事一条龙办理,白事布置
2026年年轻人如何看待彩礼与嫁妆,传统习俗在现代社会有哪些新变化?
2026年年轻人如何看待彩礼与嫁妆,传统习俗在现代社会有哪些新变化?