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>
相关推荐
小明记账簿2 分钟前
JavaScript浮点数精度问题及解决方案
开发语言·javascript·ecmascript
北辰alk15 分钟前
Vue3 事件修饰符深度解析:从基础到高级应用的完整指南
vue.js
北辰alk18 分钟前
Vue3 服务端渲染 (SSR) 深度解析:从原理到实践的完整指南
vue.js
1024肥宅40 分钟前
JavaScript性能与优化:手写实现关键优化技术
前端·javascript·面试
一字白首42 分钟前
Vue 项目实战,从注册登录到首页开发:接口封装 + 导航守卫 + 拦截器全流程
前端·javascript·vue.js
前端西瓜哥1 小时前
平面几何:如何绘制一个星形?
前端
北辰alk1 小时前
Vue3 组件懒加载深度解析:从原理到极致优化的完整指南
vue.js
天天扭码1 小时前
解放双手!使用Cursor+Figma MCP 高效还原响应式设计稿
前端·mcp
沐浴露z1 小时前
详解Javascript精度丢失以及解决方案
java·javascript
今天不要写bug1 小时前
基于qrcode前端实现链接转二维码的生成与下载
前端·javascript·typescript·vue