学习Vue 3.0中的onMounted和onUnmounted钩子函数
warning:
这篇文章距离上次修改已过191天,其中的内容可能已经有所变动。
<template>
<div>
<button @click="start">开始计时</button>
<button @click="stop">停止计时</button>
</div>
</template>
<script>
import { ref, onMounted, onUnmounted } from 'vue';
export default {
setup() {
const intervalId = ref(null);
const start = () => {
if (intervalId.value) return;
intervalId.value = setInterval(() => {
console.log('计时器运行中...');
}, 1000);
};
const stop = () => {
if (intervalId.value) {
clearInterval(intervalId.value);
intervalId.value = null;
}
};
// 组件挂载时启动计时器
onMounted(start);
// 组件卸载时清除计时器
onUnmounted(stop);
return {
start,
stop
};
}
};
</script>
这个例子中,我们使用了Vue 3.0的Composition API。setup
函数返回了两个方法start
和stop
,分别用于启动和停止计时器。onMounted
和onUnmounted
则分别在组件挂载和卸载时调用这些方法。这样的实践可以确保计时器在组件不再使用时被清理,避免内存泄漏。
评论已关闭