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>