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>
相关推荐
Giser探索家1 小时前
低空智航平台技术架构深度解析:如何用AI +空域网格破解黑飞与安全管控难题
大数据·服务器·前端·数据库·人工智能·安全·架构
gnip2 小时前
前端实现自动检测项目部署更新
前端
John_ToDebug3 小时前
JS 与 C++ 双向通信实战:基于 WebHostViewListener 的消息处理机制
前端·c++·chrome
gnip3 小时前
监听设备网络状态
前端·javascript
As33100104 小时前
Chrome 插件开发实战:打造高效浏览器扩展
前端·chrome
xrkhy4 小时前
nvm安装详细教程(卸载旧的nodejs,安装nvm、node、npm、cnpm、yarn及环境变量配置)
前端·npm·node.js
IT毕设实战小研5 小时前
基于SpringBoot的救援物资管理系统 受灾应急物资管理系统 物资管理小程序
java·开发语言·vue.js·spring boot·小程序·毕业设计·课程设计
德育处主任5 小时前
p5.js 3D盒子的基础用法
前端·数据可视化·canvas
前端的阶梯6 小时前
为何我的figma-developer-mcp不可用?
前端
weixin_456904276 小时前
Vue3入口文件main.js解析
前端·javascript·vue.js