English 中文(简体)
加载页面时如何在svelte中显示加载程序
原标题:how to show a loader in svelte when page is loading

我们有以下方法可以知道页面是否在sveltekit中加载:

import { navigating } from  $app/stores 

它在苗条(即没有苗条)中的等价物是什么?

如何在前端实现此功能。

问题回答

在Svelte中没有“对等”,因为Svelte本身只是用于组件,没有路由。

您可以收听beforeunload事件来了解我们何时开始导航。在此StackOverflow答案

我们还可以通过在Svelte可读存储中侦听事件来创建自己的导航存储器。

您可以复制此代码块:

import { readable } from  svelte/store ;

export const navigating = readable(false, (set) => {
    // Make sure that window exists
    if (typeof window ===  undefined ) return;

    const navigatingStarted = () => {
        // Notify subscribers that we are now navigating
        set(true);

        // If page hasn t  unload  event hasn t fired in 500ms, it s probably cancelled
        let unloaded = false;
        const confirmUnloaded = () => (unloaded = true);
        window.addEventListener( unload , confirmUnloaded);
        window.setTimeout(() => {
            if (!unloaded) {
                set(false);
                window.removeEventListener( unload , confirmUnloaded);
            }
        }, 500);
    };

    window.addEventListener( beforeunload , navigatingStarted);
    return () => window.removeEventListener( beforeunload , navigatingStarted);
});

然后这样使用:

<script>
  import { navigating } from  ./navigate-store 
</script>

<p>Demo:</p>
<p>
    {#if $navigating}
        Navigating!
    {:else}
        Not navigating!
    {/if}
</p>

您可以在Stacklitz中看到一个工作示例(从技术上讲,此演示在SveltKit应用程序中运行,但<;a/>;超链接具有rel=”external“,因此它们实际上并没有使用Svelt基特路由器)





相关问题
Rollup: Change the output destination of an input html file

While building I wish to change the output destination to an input file when using rollup+vite. An Example MVE: Input src/ | foo/ | | foo.html | bar | | bar.css Desired Output dist/ | foo.html | ...

ckeditor 5 plugins not working with svelte

I m trying to get ckeditor with html support to work within svelte. <script> import { onMount } from svelte ; import ClassicEditor from @ckeditor/ckeditor5-build-classic ; import {...

vite building issue for svelte-kit

Everytime I run : npm run dev in my terminal, I get this error: > enhanzer@0.0.1 dev > vite dev Forced re-optimization of dependencies Error: Failed to scan for dependencies from entries: C:...

TanStack Svelte Table Pagination

I was using TanStack Table Svelte Library and I wanted to use pagination but they haven t given any example on that, if anyone has any idea how to use the pagination on the Svelte table or if there ...

热门标签