欢迎光临殡葬网
详情描述

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年能如何帮助管理空气质量?
襄阳市殡仪服务-租冰棺,是您的放心选择
襄阳市殡仪服务-租冰棺,是您的放心选择
在异地去世的情况下,如何了解和申请运用现地的惠民殡葬政策?
在异地去世的情况下,如何了解和申请运用现地的惠民殡葬政策?
2026年各地共有产权住房政策有何差异,哪些城市更容易申请?
2026年各地共有产权住房政策有何差异,哪些城市更容易申请?
在食用当季蔬果时,有哪些有效的家庭处理方法可以减少农残疑虑?
在食用当季蔬果时,有哪些有效的家庭处理方法可以减少农残疑虑?
因手机信号或系统问题导致无法按时核销,会被误判为爽约吗?
因手机信号或系统问题导致无法按时核销,会被误判为爽约吗?
2026年中考综合素质评价越来越重要,小学阶段该怎么帮孩子攒素材?
2026年中考综合素质评价越来越重要,小学阶段该怎么帮孩子攒素材?
当有意外收入时,将其转为储蓄而非消费的心理技巧有哪些?
当有意外收入时,将其转为储蓄而非消费的心理技巧有哪些?
对于刚参加工作不久的年轻人,租房提取住房公积金有哪些便利条件与渠道?
对于刚参加工作不久的年轻人,租房提取住房公积金有哪些便利条件与渠道?
近年有哪些新兴的行业或赛道获得了更多的创业政策倾斜?
近年有哪些新兴的行业或赛道获得了更多的创业政策倾斜?
过桥垫资费用如何核算?结合计费规则看懂单日收费与总成本计算
过桥垫资费用如何核算?结合计费规则看懂单日收费与总成本计算
房产抵押贷款相关法规解读,学法懂法保障抵押借贷行为合法合规
房产抵押贷款相关法规解读,学法懂法保障抵押借贷行为合法合规
台风来临前窗外突然变得安静,真的是风暴已经过去了吗?
台风来临前窗外突然变得安静,真的是风暴已经过去了吗?
押车贷款办理流程详解,签订借据时借款用途怎么填写?
押车贷款办理流程详解,签订借据时借款用途怎么填写?
大暑三候
大暑三候"腐草为萤、土润溽暑、大雨时行"该怎么理解?
解读相关法律法规对“最终解释权归本店所有”这类单方声明的具体规定
解读相关法律法规对“最终解释权归本店所有”这类单方声明的具体规定
2026年有没有更智能的个人收款码账单管理与分析工具?
2026年有没有更智能的个人收款码账单管理与分析工具?
房产证红本抵押贷款办理流程全解析,从申请到放款只需七步
房产证红本抵押贷款办理流程全解析,从申请到放款只需七步
头伏饺子二伏面三伏烙饼摊鸡蛋,这套吃法背后是哪里的民俗习惯?
头伏饺子二伏面三伏烙饼摊鸡蛋,这套吃法背后是哪里的民俗习惯?