[英]In Vue V2, how do I merge two arrays of objects and save them to local storage?
[英]How do I save objects that I push into an array, then display them using local storage?
我正在嘗試僅使用html和javascript制作一個簡單的購物車。 我的購物車中有一個空數組,並且有一個名為product1的對象。 我有一個click事件,它將對象名稱和價格推入數組,然后使用innerHTML顯示它。 我想知道在使用本地存儲刷新頁面時如何將物品保存在購物車中?
Here is my javascript code.
var cart = [];
var product1 = {
name: "product1",
price: 90.00
};
document.getElementById("cart-button").addEventListener("click", addToCart);
function addToCart() {
cart.push(product1.name + "<br />" + product1.price);
document.getElementById("cart-contents").innerHTML = cart;
}
在將商品添加到購物車時,必須將其保存在localStorage中。 重新加載時,購物車變量從localStorage加載購物車。 如果沒有localStorage var cart,它將得到一個空數組。
var cart = JSON.parse(localStorage.getItem('cart')) || [];
var product1 = {
name: "product1",
price: 90.00
};
document.getElementById("cart-button").addEventListener("click", addToCart);
function addToCart() {
cart.push(product1.name + "<br />" + product1.price);
localStorage.setItem('cart', JSON.stringify(cart));
document.getElementById("cart-contents").innerHTML = cart;
}
更新時,您需要將購物車存儲為json字符串。 您可以使用JSON.parse()
在加載時對其進行解析
var cart = JSON.parse(localStorage.getItem('cart')) || [];
var product1 = {
name: "product1",
price: 90.00
};
document.getElementById("cart-button").addEventListener("click", addToCart);
function addToCart() {
cart.push(product1.name + "<br />" + product1.price);
localStorage.setItem('cart', cart);
document.getElementById("cart-contents").innerHTML = cart;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.