develop stop watch applicaiton , counter, stop , reset ; click on start start the counter, clikc on stoop , rest to 0,resume develop in vuejs compositon api
==
<template>
<div>
<p>{{ timer }}</p>
<button @click="startTimer" :disabled="isRunning">Start</button>
<button @click="stopTimer" :disabled="!isRunning">Stop</button>
<button @click="resetTimer">Reset</button>
</div>
</template>
<script>
import { ref, watch, onUnmounted } from 'vue';
export default {
setup() {
const timer = ref(0);
const isRunning = ref(false);
let intervalId = null;
const startTimer = () => {
if (!isRunning.value) {
isRunning.value = true;
intervalId = setInterval(() => {
timer.value++;
}, 1000);
}
};
const stopTimer = () => {
clearInterval(intervalId);
isRunning.value = false;
};
const resetTimer = () => {
clearInterval(intervalId);
timer.value = 0;
isRunning.value = false;
};
// Cleanup interval on component unmount
onUnmounted(() => {
clearInterval(intervalId);
});
// Watch for changes in isRunning to update the UI
watch(isRunning, (newValue) => {
if (!newValue && timer.value !== 0) {
clearInterval(intervalId);
}
});
return {
timer,
isRunning,
startTimer,
stopTimer,
resetTimer,
};
},
};
</script>
No comments:
Post a Comment