在 sveltekit 中,如何使用 __layout.svelte 文件在槽中传递道具?

aja*_*ani 9 svelte sveltekit

在 __layout 文件中,我想传递一个变量,比如 btnclicked="HR",并且我想在 Slot 中渲染的组件中收集相同的变量?请帮忙怎么做?

Eva*_*son 2

如果你想传递反应性的数据,那么我认为这样做的方法是使用带有 Context 的 Svelte 存储。

// in __layout.svelte
  <script>
    import { setContext } from 'svelte';
    import { writable } from 'svelte/store';

    const btnClicked = writable('');

    setContext('btnClicked', btnClicked);

    //...some code that sets the btnClicked store value
  </script>

  <slot />

// in child.svelte
  <script>
    import { getContext } from 'svelte';

    const btnClicked = getContext('btnClicked');

    // use $btnClicked in this component to access the value
  </script>
Run Code Online (Sandbox Code Playgroud)