Svelte 中的条件渲染

Conditional Rendering in Svelte

我正在尝试根据表单中的值有条件地呈现表单中的字段。我在这里创建了一个示例:

https://svelte.dev/repl/54917929b89646339a9c7498c13f7b38?version=3.17.3

问题的要点是我正在创建一个控件并使用其 slot,其中包含一些条件逻辑。

上下文在 Svelte 中不是反应式的,这意味着不跟踪值的变化。你需要一些反应性的东西,让视图做出反应。

你可以做的是在上下文中放置一个 store

例如,在App.svelte中:

    import { setContext } from 'svelte'
    import { writable } from 'svelte/store'
    let data = writable({});
    setContext("data", data);

然后,在子组件的更深处(注意$前缀来读取/写入模板中的存储值):

  let data = getContext("data");

  const handleInput = event => {

    // NOTE the dollar prefix to access the value
    $data[fieldName] =
      event.target.type === "checkbox"
        ? event.target.checked
        : event.target.value;
  };

REPL using store in context

另一种方法是简单地使用 two way binding.

App.svelte中:

<script>
    // ...
    let data = {};
</script>

<Form submit={submit}>
    <FormField bind:data ... />
    {#if data.type && data.type === 'Local'}
        <FormField bind:data ... />
    {/if}
</Form>

在你的 FormField.svelte 中:

    export let data

REPL using binding