webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.69k stars 188 forks source link

10 - 生命周期钩子 #2726

Open Ly-TiR opened 2 months ago

Ly-TiR commented 2 months ago
<script setup lang="ts">
import { onMounted, inject, onBeforeUnmount } from 'vue';

const timer = inject('timer');
const count = inject('count');

onMounted(() => {
  timer.value = window.setInterval(() => {
    count.value++;
  }, 1000);
});

onBeforeUnmount(() => {
  if (timer.value) clearInterval(timer.value);
});
</script>

<template>
  <div>
    <p>Child Component: {{ count }}</p>
  </div>
</template>