我正在嘗試做一些類似于購物車的事情,最初有一系列產品,我加載了一系列物件。
products = [
{
id: 1,
name: "Product1",
},
{
id: 2,
name: "Product2",
},
{
id: 3,
name: "Product",
},
];
我用這樣的苗條顯示產品串列:
<div class="col-md-12 row grid">
{#each products as product}
<div class="card mt-2 g-col-3">
<div class="row">
<div class="col-md-8">
<div class="card-body">
<h5>{product.name}</h5>
<button
on:click={addProduct(product.id)}
class="btn btn-primary">Add Product
</button>
{ "0 products"}
</div>
</div>
</div>
</div>
{/each}
</div>
并通過函式 addProduct() 我使用產品 id 和該產品的單位數更新陣列庫存
let inventory =[];
const addProduct = id =>{
let qty = 0;
if(inventory.find(element => element.id === id))
{
qty = inventory.find(element => element.id === id).qty
inventory=inventory.filter(element => element.id !== id)
inventory.push({id:id,qty:qty 1});
}
else{
inventory.push({id:id,qty:1});
}
}
我不知道如何在每個產品中設定它,現在它顯示 {“0 products”},在用戶添加每個產品時動態更新它
非常感謝 !
uj5u.com熱心網友回復:
我了解{ "0 products"}您希望顯示庫存中的物品數量。您可以通過將其替換為
{inventory.find(element => element.id === product.id)?.qty ?? 0} products
使用了可選鏈接 (?.)和空值合并運算子 (??)
除了您希望在進行編輯(如推送專案)之后分配inventory給自身以觸發重新渲染之外,在addProduct(). 如果已經有一個元素,您不想推送另一個元素,而是編輯現有元素,這給出
function addProduct(id) {
const element = inventory.find(element => element.id === id)
if(element) {
element.qty = 1
inventory = inventory
}
else{
inventory.push({id:id,qty:1});
inventory = inventory
}
}
雖然這可行 - 請參閱這個 REPL - 我會考慮將清單設為物件而不是陣列,因為檢查條目并編輯它們有點“更快”,比較這個REPL(條目總是可以很容易地使用迭代Object.entries/.keys/.values(inventory))
<script>
import {products} from './products'
let inventory = {}
function addProduct(id) {
const entry = inventory[id]
if(entry) {
entry.qty = 1
inventory = inventory
}
else{
inventory[id] = {qty:1}
inventory = inventory
}
}
</script>
<div>
{#each products as product}
<h5>{product.name}</h5>
<button on:click={() => addProduct(product.id)}>
Add Product
</button>
{inventory[product.id]?.qty ?? 0} products
{/each}
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/454368.html
標籤:javascript 数组 目的 苗条
下一篇:如何解決谷歌表格公式問題
