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>
相关推荐
前端一课6 分钟前
Vue3 的 Composition API 和 Options API 有哪些区别?举例说明 Composition API 的优势。
前端
用户47949283569156 分钟前
都说node.js是事件驱动的,什么是事件驱动?
前端·node.js
晴殇i7 分钟前
前端架构中的中间层设计:构建稳健可维护的组件体系
前端·面试·代码规范
申阳26 分钟前
Day 7:05. 基于Nuxt开发博客项目-首页开发
前端·后端·程序员
Crystal32833 分钟前
App端用户每日弹出签到弹窗如何实现?(uniapp+Vue)
前端·vue.js
摸着石头过河的石头35 分钟前
Service Worker 深度解析:让你的 Web 应用离线也能飞
前端·javascript·性能优化
用户40993225021235 分钟前
Vue 3中watch侦听器的正确使用姿势你掌握了吗?深度监听、与watchEffect的差异及常见报错解析
前端·ai编程·trae
1024小神38 分钟前
Xcode 常用使用技巧说明,总有一个帮助你
前端
molly cheung40 分钟前
Vue3:watch与watchEffect的异同
vue.js·watch·store·watcheffect
政采云技术1 小时前
音视频通用组件设计探索和应用
前端·音视频开发