【发布时间】:2021-05-07 07:26:10
【问题描述】:
我对 Svelte 和前端比较陌生,我正在构建一个产品目录的小型演示。该应用程序执行 api 请求并获取一些 json 数据并生成包含产品的网格并将一些数据填充到每个产品中。我试图弄清楚如何更改每个项目的数量。每次单击加号按钮时,只有该按钮所属的产品的数量应该改变。例如,当第一个商品的加号按钮被点击时,只减少它自己的数量,而不是所有其他商品。如果仅该产品数量变为零,则该按钮将变为非活动状态。代码如下:
import { onMount } from 'svelte';
let products = [];
let total = 0;
let quantity = 5;
onMount(async () => {
const res = await fetch(`https://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline`);
products = await res.json();
});
function increment(price){
total= total + price;
console.log(total);
quantity = quantity - 1;
}
function decrement(price){
total= total - price;
console.log(total);
quantity = quantity + 1;
}
</script>
<h1>Photo album</h1>
<div class="photos">
{#each products as product}
<figure>
<img src={product.image_link} alt={product.name}>
<figcaption>{product.name}</figcaption>
<small>{product.price}<small/>
<h1>Quantity: {quantity}</h1>
<button on:click={increment(parseFloat(product.price))}>+</button>
<button on:click={decrement(parseFloat(product.price))}>-</button>
</figure>
{:else}
<p>loading...</p>
{/each}
</div>
<div>
<h1>Total {total}</h1>
</div>
<style>
.photos {
width: 100%;
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-gap: 8px;
}
figure, img {
width: 100%;
margin: 0;
}
</style> ```
【问题讨论】:
标签: list components svelte items svelte-component