这就是我在页面的html中拥有的内容:
{#each subCategories as subCategories}
{#key $cart}
{($cart.indexOf(subCategories.name) > -1)}
{#if ($cart.indexOf(subCategories.name) > -1)}
Test
{:else}
<div class="media ali list-group-item list-group-item-action clique" on:click={() => changeCart(subCategories.name)}>
<div class="media-left">
<Management/>
</div>
<div class="media-body" >
<h4 class="media-heading">{subCategories.name}</h4>
</div>
</div>
{/if}
{/key}
{/each}
对于js部分,这就是我所拥有的:
import { writable } from "svelte/store";
let cart = writable([]);
function changeCart(subCat) {
$cart.push(subCat);
console.log($cart);
}
但问题是,if条件不会重新加载/呈现另一次,而案例的更改只有在返回到前一个组件并再转到该组件之后才能工作。
发布于 2022-03-08 07:40:50
,因为Svelte的反应性是由赋值触发的,使用像push和splice这样的数组方法不会自动导致更新。
来源:https://svelte.dev/tutorial/updating-arrays-and-objects
解决方案:
import { writable } from 'svelte/store';
let cart = writable([])
function changeCart(subCat)
{
// $cart.push(subCat)
$cart = [...$cart, subCat]
console.log($cart)
}
https://stackoverflow.com/questions/71397596
复制