Svelte 生命周期函数全例子演示

正文

用一个例子演示 Svelte 中所有生命周期函数的用法(实际上就是记几个单词)。

下面是父组件:App.svelte,子组件的挂载、卸载都靠它触发:

<script>
  import Child from "./Child.svelte";

  // state
  let status = false;

  // computed
  $: desc = status ? "销毁子组件" : "挂载子组件";

  // methods
  const toggle = () => (status = !status);
</script>

{#if status}
  <Child />
{/if}

<button on:click={toggle}>{desc}</button>

下面是子组件,值得注意的有两点:

  1. beforeUpdate 和 afterUpdate 在创建之前就会触发
  2. tick() 函数功能类似 Vue 的 this.$nextTick
<script>
  import { onMount, onDestroy, beforeUpdate, afterUpdate, tick } from "svelte";

  nextTick();

  // state
  let status = false;

  // computed
  $: updateVal = status ? " ,我更新啦!" : "";

  // life cycle
  onMount(() => {
    alert("子组件创建好啦");
    setTimeout(() => {
      status = true;
    }, 5000);
    // 在组件销毁时调用, 调用时机晚于 onDestroy
    return () => {
      alert("子组件被销毁咯");
    };
  });

  onDestroy(() => {
    alert("正经的卸载函数");
  });

  beforeUpdate(() => {
    alert("组件即将更新咯");
  });

  afterUpdate(() => {
    alert("组件已经更新啦");
  });

  // methods
  async function nextTick() {
    await tick();
    alert("下一个 Tick 触发");
  }
</script>

<h1>我是子组件{updateVal}</h1>

总结

触发顺序:beforeUpdate、onMount、afterUpdate、tick()、beforeUpdate()、afterUpdate()、onDestroy()

参考

原文地址:https://www.cnblogs.com/aisowe/p/15245569.html