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>
相关推荐
恶猫几秒前
javascript文本长度检测与自动截取,用于标题长度检测
javascript·css·css3·js·自动检测·文本长度
IAtlantiscsdn10 分钟前
Redis7底层数据结构解析
前端·数据结构·bootstrap
小枫编程10 分钟前
Spring Boot 与前端文件上传跨域问题:Multipart、CORS 与网关配置
前端·spring boot·后端
uhakadotcom1 小时前
入门教程:如何编写一个chrome浏览器插件(以jobleap.cn收藏夹为例)
前端·javascript·面试
捡芝麻丢西瓜1 小时前
SPM 之 混编(OC、Swift)项目保姆级教程(Swift Package Manager)
前端
我是天龙_绍1 小时前
cdn是个啥?
前端
南雨北斗1 小时前
VSCode三个TS扩展工具介绍
前端
若无_1 小时前
了解 .husky:前端项目中的 Git Hooks 工具
前端·git
ze_juejin1 小时前
前端发送语音方式总结
前端
给月亮点灯|1 小时前
Vue3基础知识-Hook实现逻辑复用、代码解耦
前端·javascript·vue.js