如何在 svelte storybook 中使用 `slot`

How to use `slot` in svelte storybook

如何为带有插槽的以下组件添加 svelte storybook 故事。

Button.svelte
<button>
 <slot />
</button>

我可以用作

<script>
  import Button from './Button.svelte';
</script>

<Button>Hello World</Button>

如何为其中包含 slots 的组件创建故事?

根据官方故事书库中的 example file

If we need to test components in a Svelte environment, for instance to test slot behaviour, then wrapping the component up in a view made just for the story is the simplest way to achieve this.

所以暂时遵循这个建议可能是最容易的。

Stack.svelte

  <div class="flex-col">
      <slot><!-- optional fallback --></slot>
  </div>

StackView.svelte

<script lang="ts">
  import Stack from './Stack.svelte'

</script>

<Stack>
  <p>Slot 1</p>
  <p>Slot 2</p>
  <p>Slot 3</p>
</Stack>

stack.stories.js

import Stack from './StackView.svelte';

export default {
  title: 'Stack',
  component: Stack,
};


const Template = ({ ...args }) => ({
  Component: Stack,
  props: args,

});

export const Regular = Template.bind({});

也就是说,很快就有可能 use svelte template syntax to write stories。我认为这样可以更优雅地解决问题。

我使用 npx sb init 命令将故事书添加到我的 svelte 组件库中。以下故事定义适用于我的 SuccessLabel 组件:

<!--SuccessLabel.svelte-->
<div>
 <slot />
</div>

<style>
 div {
    position: relative;
    color: white;
    background-color: #28a745;
    border-color: #28a745;
    margin-top: -3px;
    padding: 10px;
    border-radius: 5px;
    border-top-right-radius: 0px;
    border-top-left-radius: 0px;
    font-size: 12px;
  }
</style>


<!--SuccessLabel.stories.svelte-->
<script>
 import { Meta, Story } from "@storybook/addon-svelte-csf";
 import SuccessLabel from "../src/components/labels/SuccessLabel.svelte";
</script>

<Meta title="Labels/SuccessLabel" component={SuccessLabel} />

<Story name="Default">
 <SuccessLabel>This message should be shown</SuccessLabel>
</Story>