Skip to content

10 - 生命周期钩子 #2252

Open
Open
@mu-muw

Description

@mu-muw
添加一个卸载组件就好

Child Component: {{ count }}

<script setup> import { onMounted, onUnmounted, inject } from "vue" const timer = inject("timer") // 从父组件注入的定时器 const count = inject("count") // 从父组件注入的计数器 // 切换子组件时, 定时器将不正常工作, 让我们来修复它 . onMounted(() => { // 当组件挂载时执行 timer.value = window.setInterval(() => { // 设置定时器,每隔 1000 毫秒执行一次 count.value++ // 计数器加一 }, 1000) })

onUnmounted(() => { // 当组件卸载时执行
clearInterval(timer.value) // 清除定时器
})
</script>

// 你的答案

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions