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>
相关推荐
Codebee几秒前
使用Qoder 改造前端UI/UE升级改造实践:从传统界面到现代化体验的华丽蜕变
前端·人工智能
叶落阁主4 分钟前
Neovim 插件 i18n.nvim 介绍
java·vue.js·vim
叫我詹躲躲4 分钟前
开发提速?Vue3模板隐藏技巧来了
前端·vue.js·ai编程
华仔啊4 分钟前
面试都被问懵了?CSS 的 flex:1 和 flex:auto 真不是一回事!90%的人都搞错了
前端·javascript
前端康师傅7 分钟前
JavaScript 函数详解
前端·javascript
金金金__9 分钟前
antd v5 support React is 16 ~ 18. see https://u.ant.design/v5-for-19 for...
前端
葡萄城技术团队10 分钟前
从基础到实战:一文吃透 JS Tuples 与 Records 的所有核心用法
javascript
会豪10 分钟前
工业仿真(simulation)--前端(二)-资源管理器
前端
@小红花1 小时前
从0到1学习Vue框架Day03
前端·javascript·vue.js·学习·ecmascript
前端与小赵1 小时前
vue3中 ref() 和 reactive() 的区别
前端·javascript·vue.js