【问题标题】:Conditional Rendering in SvelteSvelte 中的条件渲染
【发布时间】:2020-01-25 08:47:18
【问题描述】:

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

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

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

【问题讨论】:

    标签: svelte


    【解决方案1】:

    上下文在 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

    【讨论】:

    • 感谢您的精彩回答!奇迹般有效。你认为这个例子适合文档中的“例子”吗?
    猜你喜欢
    • 1970-01-01
    • 2021-09-11
    • 2020-12-05
    • 1970-01-01
    • 2021-12-13
    • 2021-04-15
    • 2019-12-26
    • 2020-05-10
    • 2019-11-26
    相关资源
    最近更新 更多