页面的生命周期基本事件
Every component in Svelte fires several lifecycle events that we can hook into that help us implement the functionality we have in mind.
Svelte中的每个组件都会触发多个生命周期事件,我们可以将其挂钩,以帮助我们实现所想到的功能。
In particular, we have
特别是,我们有
onMount
fired after the component is rendered渲染组件后触发
onMount
onDestroy
fired after the component is destroyed销毁组件后触发
onDestroy
beforeUpdate
fired before the DOM is updated在DOM更新之前触发了
beforeUpdate
afterUpdate
fired after the DOM is updatedDOM更新后触发
afterUpdate
We can schedule functions to happen when these events are fired by Svelte.
我们可以安排函数在Svelte触发这些事件时发生。
We don’t have access to any of those methods by default, but we can import them from the svelte
package:
默认情况下,我们无权访问任何这些方法,但是我们可以从svelte
包中导入它们:
<script>
import { onMount, onDestroy, beforeUpdate, afterUpdate } from 'svelte'
</script>
A common scenario for onMount
is to fetch data from other sources.
onMount
的常见方案是从其他来源获取数据。
Here’s a sample usage of onMount
:
这是onMount
的示例用法:
<script>
import { onMount } from 'svelte'
onMount(async () => {
//do something on mount
})
</script>
onDestroy
allows us to clean up data or stop any operation we might have started at the component initialization, like timers or scheduled periodic functions using setInterval
.
onDestroy
允许我们清理数据或停止在组件初始化时可能已开始的任何操作,例如使用setInterval
计时器或计划的定期函数。
One particular thing to notice is that if we return a function from onMount
, that serves the same functionality of onDestroy
- it’s run when the component is destroyed:
需要注意的一件事是,如果我们从onMount
返回一个函数,该函数提供与onDestroy
相同的功能-它在组件销毁时运行:
<script>
import { onMount } from 'svelte'
onMount(async () => {
//do something on mount
return () => {
//do something on destroy
}
})
</script>
Here’s a practical example that sets a periodic function to run on mount, and removes it on destroy:
这是一个实际的示例,该示例将周期函数设置为在安装时运行,并在销毁时将其删除:
<script>
import { onMount } from 'svelte'
onMount(async () => {
const interval = setInterval(() => {
console.log('hey, just checking!')
}, 1000)
return () => {
clearInterval(interval)
}
})
</script>
页面的生命周期基本事件