Creating a Product Item Component and use it
Create a new file with the following contents
components/ProductItem
export default class ProductItem extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
const template = document.getElementById("product-item-template");
const content = template.content.cloneNode(true);
this.appendChild(content);
const product = JSON.parse(this.dataset.product);
this.querySelector("h4").textContent = product.name;
this.querySelector("p.price").textContent = `$${product.price.toFixed(2)}`;
this.querySelector("img").src = `data/images/${product.image}`;
this.querySelector("a").addEventListener("click", event => {
console.log(event.target.tagName);
if (event.target.tagName.toLowerCase()=="button") {
//TODO
} else {
app.router.go(`/product-${product.id}`);
}
event.preventDefault();
})
}
}
customElements.define("product-item", ProductItem);
Now in the placeholder of MenuPage
let's use it
category.products.map(product => {
const item = document.createElement("product-item");
item.dataset.product = JSON.stringify(product);
liCategory.querySelector("ul").appendChild(item);
});