如何在 svelte 中的 html 标记中的 If 条件后强制渲染
How to force render after an If condition in the html tag in svelte
这是我页面 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 条件不会重新加载/再次渲染,并且只有在返回到前一个组件并再次转到该组件后,大小写的更改才会起作用。
Because Svelte's reactivity is triggered by assignments, using array
methods like push and splice won't automatically cause updates.
来源: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)
}
这是我页面 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 条件不会重新加载/再次渲染,并且只有在返回到前一个组件并再次转到该组件后,大小写的更改才会起作用。
Because Svelte's reactivity is triggered by assignments, using array methods like push and splice won't automatically cause updates.
来源: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)
}