【问题标题】:Svelte: How do I call a function in a child component after switching to it using a dynamic component?Svelte:如何在使用动态组件切换到子组件后调用子组件中的函数?
【发布时间】:2021-09-08 11:02:40
【问题描述】:

我的父组件中有一个<svelte:component>,它允许我在多个子组件之间切换。我想在其中一个子组件中调用一个函数。为此,我在父组件中有一个函数,它首先尝试切换到该子组件,然后调用该函数。

App.svelte

<script>
    import First from './First.svelte'
    import Second from './Second.svelte'
    
    let selected = First;
    let child;
    
    function secondHello() {
        selected = Second;
        child.hello();
    }
</script>

...

<svelte:component this={selected} bind:this={child}/>

Second.svelte

<script>
    export function hello() {
        //do stuff
    }
</script>

回复:https://svelte.dev/repl/93214917d7414741a229cd81267287b7?version=3.38.3

问题是当当前选中的组件不是Second时,函数secondHello不起作用。在更改 selected 之后,child 似乎需要一些时间才能更新,导致 child.hello(); 引发错误,因为它在其他子组件中不存在。

有什么方法可以等待child 更新吗?还是我应该使用不同的方法?

【问题讨论】:

    标签: svelte svelte-component


    【解决方案1】:

    您的猜测是正确的,child.hello() 触发得太快了,因为 Svelte 尚未刷新更新,因此 bind:this={child} 尚未更新 child。对于这样的情况,Svelte 提供了tick 方法,让您可以等到任何挂起的状态更新应用到 DOM:

    <script>
        import { tick } from 'svelte'
        import First from './First.svelte'
        import Second from './Second.svelte'
        
        let selected = First;
        let child;
        
        function secondHello() {
            selected = Second;
            tick().then(() => child.hello());
        }
        
        // or:
        async function secondHello() {
            selected = Second;
            await tick();
            child.hello();
        }
    </script>
    
    ...
    
    <svelte:component this={selected} bind:this={child}/>
    

    tick教程:https://svelte.dev/tutorial/tick

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 2021-04-07
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      相关资源
      最近更新 更多