如何使用 Composition API 将项目添加到本地存储 Vue 3

How to add item to local storage Vue 3 with Composition API

我正在尝试将购物车项目添加到 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 是否不为 null 以及何时不为 null 我想将其他产品添加到购物车产品项目的现有状态,所以尝试这样:

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.

来表示购物车状态的存储。

也许你们中的一些人知道一些很酷的 material,它们将向您展示如何使用组合 API.

正确地创建购物车

谢谢!

需要设置ref值,还要解析本地存储值

let cartItems = ref([])
if (window.localStorage.getItem('CART') !== null) {
    cartItems.value = JSON.parse(window.localStorage.getItem('CART'));
}

我认为您应该在代码中使用 cartItems.value:

let cartItems = ref([])
if (window.localStorage.getItem('CART') !== null) {
    cartItems.value = window.localStorage.getItem('CART')
}