Open
Description
<!-- app.vue -->
<script setup lang="ts">
import { ref, provide } from "vue"
import Child from "./Child.vue"
const visible = ref(true)
const timer = ref(null)
const count = ref(0)
provide("timer", { timer } )
provide("count", { count } )
function toggle() {
visible.value = !visible.value
}
</script>
<template>
<div>
<Child v-if="visible" />
<p>
<button @click="toggle">
Toggle Child Component
</button>
</p>
</div>
</template>
<!-- Child.vue -->
<script setup lang="ts">
import { onUnmounted } from "vue";
import { onMounted, inject } from "vue"
const { timer } = inject<{timer: any}>("timer") || {};
const { count } = inject<{ count: any }>("count") || {};
onMounted(() => {
timer.value = window.setInterval(() => {
count.value++
}, 1000)
})
onUnmounted(() => {
clearInterval(timer.value);
});
</script>
<template>
<div>
<p>
Child Component: {{ count }}
</p>
</div>
</template>