【问题标题】:svelte keep updating store var without clicking to updatesvelte 不断更新 store var 而不点击更新
【发布时间】:2021-02-20 22:29:48
【问题描述】:

我的应用会自动更新 $content 值,而无需我点击按钮。我知道这是一个简单的问题,但我不知道为什么,我正在学习苗条。

App.svelte

<script>
    import { content } from './store.js';
    import Item from './Item.svelte';


    $content = [{ id:0,obj: "Fell free to browse any category on top." }];

    function addContent(value) {
        $content = [{ id:0,obj: value}]
    }
</script>
<li><button on:click={addContent("Home Page")}>Home</button></li>
<li><button on:click={addContent("Products Page")}>Products</button></li>

<div class="Content">
    <p>Fell free to browse any category on top.</p>
    {#each $content as item}
        <p><svelte:component this={Item} objAttributes={item} /></p>
    {/each}
</div>

store.js

import { writable } from 'svelte/store';
export let content = writable({});

Item.svelte

<script>
    import { fade } from 'svelte/transition';
    export let objAttributes = {};
    
</script>
<p transition:fade>
    {objAttributes.obj} 
    {#if objAttributes.otherattrib}<em>{objAttributes.otherattrib}</em>{/if}
</p>

【问题讨论】:

    标签: svelte-3 svelte-store


    【解决方案1】:

    这是因为您的 on:click 事件定义错误。 on:click 将这样的函数作为参数

    <button on:click={functionGoesHere}>
    

    或者,如果你想内联

    <button on:click={() => { }>
    

    在您的情况下发生的是您直接调用一个函数,然后单击按钮时将调用该函数的结果。您可以在此示例中看到:

    <script>
      function createFn() {
        return () => console.log('logging this')
      }
    </script>
    <button on:click={createFn}>Click here</button>
    

    在本例中,函数() =&gt; console.log('logging this') 将附加到按钮上。

    所以回到你的代码,这很容易通过将其设置为函数而不是函数调用来解决:

    <li><button on:click={() => addContent("Home Page")}>Home</button></li>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      相关资源
      最近更新 更多