Skip to content

10 - Lifecycle Hooks #2959

Open
Open
@Rockchtaa

Description

@Rockchtaa
//child

<script setup lang="ts">
import { onMounted, onUnmounted, inject } from "vue"

const timer = inject("timer")!
const count = inject("count")!

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

onUnmounted(() => {
  clearInterval(timer.value)
  timer.value = null
})
</script>

<template>
  <div>
    <p>Child Component: {{ count }}</p>
  </div>
</template>
//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>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions