vue封装useWatch hook支持停止监听和重启监听功能
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};
}
使用:
<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>