vue封装useWatch hook支持停止监听和重启监听功能

javascript 复制代码
import { watch, reactive } from 'vue';

export function useWatch(source, cb, options) {
  const state = reactive({
    stop: null
  });

  function start() {
    state.stop = watch(source, cb, options);
  }

  function stop() {
    state.stop();
    state.stop = null;
  }

  // 返回一个对象,包含start和stop方法
  return {
    start,
    stop
  };
}

使用:

javascript 复制代码
<template>
  <div>
    <p>Message: {{ message }}</p>
    <button @click="changeMessage">Change Message</button>
    <button @click="stopWatching">Stop Watching</button>
    <button @click="startWatching">Start Watching</button>
  </div>
</template>

<script>
import { reactive } from 'vue';
import { useWatch } from './useWatch';

export default {
  setup() {
    const state = reactive({
      message: 'Hello World',
      watcher: null
    });

    // 使用自定义的useWatch Hook来监听message属性
    state.watcher = useWatch(
      () => state.message,
      (newValue, oldValue) => {
        console.log('Message changed:', newValue, oldValue);
      }
    );

    function changeMessage() {
      state.message = 'Hello Vue 3';
    }

    function stopWatching() {
      state.watcher.stop();
    }

    function startWatching() {
      state.watcher.start();
    }

    return {
      message: state.message,
      changeMessage,
      stopWatching,
      startWatching
    };
  }
};
</script>
相关推荐
李剑一5 分钟前
uni-app实现leaflet地图图标旋转
前端·trae
zhengxianyi5155 分钟前
ruoyi-vue-pro优化——如何将一个模块快速变成一个独立的应用进行开发,部署,管理
vue.js·前后端分离·数据大屏·ruoyi-vue-pro优化
风度前端34 分钟前
npm 2026安全新规下的免登录发包策略
前端
冴羽1 小时前
2026 年前端必须掌握的 4 个 CSS 新特性!
前端·javascript·css
rgeshfgreh1 小时前
Python流程控制:从条件到循环实战
前端·数据库·python
狗头大军之江苏分军1 小时前
告别旧生态:Ant Design 6 不再支持 IE 与现代前端趋势解读
前端·javascript·后端
C_心欲无痕1 小时前
nginx - 开启 gzip 压缩
运维·前端·nginx
闲云一鹤1 小时前
2026 最新 ComfyUI 教程 - 本地部署 AI 生图模型 - Z-Image-Turbo
前端·人工智能·ai编程
开开心心_Every1 小时前
安卓后台录像APP:息屏录存片段,行车用
java·服务器·前端·学习·eclipse·edge·powerpoint
狗头大军之江苏分军1 小时前
Ant Design 6.0 正式发布:从 V5 到 V6 有哪些变化?
前端