页面的生命周期基本事件_苗条的生命周期事件

页面的生命周期基本事件

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 updated

    DOM更新后触发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>

翻译自: https://flaviocopes.com/svelte-lifecycle-events/

页面的生命周期基本事件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值