我正在嘗試將購物車專案添加到 Vue 3 中的 localStorage。我正在使用 Composition API,而且我只是在學習 Vue,所以請理解:D
好的,所以這是我呼叫 addProductToCart 函式的單一產品視圖代碼
export default {
props: {
id: {
required: true,
type: String
}
},
setup(props) {
const { product, getProduct } = useProducts()
onMounted(getProduct(props.id))
let cartItems = ref([])
function addProductToCart(product) {
cartItems.value.push({...product})
window.localStorage.setItem('CART', JSON.stringify(cartItems.value))
console.log(JSON.parse(localStorage.getItem('CART')));
}
return {
addProductToCart,
product
}
}
}
問題是當我重新加載頁面時。它存盤的購物車專案的狀態,但是當我在重繪 頁面后添加另一個產品時,localStorage 它被重置。
問題出在這里:
let cartItems = ref([])
我試圖檢查 localStorage 是否不為空,何時不為空我想將另一個產品添加到購物車產品專案的現有狀態,所以嘗試這樣:
let cartItems = ref([])
if (window.localStorage.getItem('CART') !== null) {
cartItems = window.localStorage.getItem('CART')
}
但是當我點擊添加到購物車按鈕時,我收到錯誤:
Uncaught TypeError: Cannot read properties of undefined (reading 'push')
我在互聯網上搜索了很多關于購物車狀態的資訊,但我發現它們使用 Composition API 表示購物車狀態的存盤沒有任何意義。
也許你們中的一些人知道一些很酷的材料,它們會向您展示如何使用 Composition API 正確創建購物車。
謝謝!
uj5u.com熱心網友回復:
您需要設定 ref 值并決議本地存盤值
let cartItems = ref([])
if (window.localStorage.getItem('CART') !== null) {
cartItems.value = JSON.parse(window.localStorage.getItem('CART'));
}
uj5u.com熱心網友回復:
我相信您應該在代碼中使用 cartItems.value:
let cartItems = ref([])
if (window.localStorage.getItem('CART') !== null) {
cartItems.value = window.localStorage.getItem('CART')
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375423.html
標籤:javascript Vue.js 本地存储 Vuejs3
上一篇:陣列減少不提供所有資料
下一篇:物件陣列到另一個陣列匯總
