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>
相关推荐
张元清9 小时前
React 19 Hooks:新特性及高效使用指南
前端·javascript·面试
敏捷建模9 小时前
Zig语言能够编写同时针对PC端和手机端自适应的软件吗
前端
Hello_Embed9 小时前
LVGL 入门(四):大小坐标与盒子模型
前端·笔记·stm32·单片机·嵌入式
༄天M宇ༀ10 小时前
E10: e-builder 低代码构建平台接口管理(E9建模版)
java·前端·spring·servlet·reactjs
窝子面10 小时前
解决vite构建的项目中使用path报错
前端
kana_yonk10 小时前
如何设置前端vue程序开机自启(Windows)
前端·vue.js·windows
清空mega10 小时前
《Vue3 中 computed、watch、watchEffect 怎么用?响应式核心能力详解》
前端·javascript·vue.js
ego.iblacat10 小时前
在 LNMP 平台中部署 Web 应用
android·前端·adb
浩宇软件开发10 小时前
springBoot+Vue中华诗词学习后台管理系统
vue.js·spring boot·axios·element-plus·router