【发布时间】:2021-07-12 03:34:14
【问题描述】:
我正在尝试使用 vuex 在购物车中添加商品,但在控制台中出现了一些错误,并且页面中的产品也没有显示。请告诉我如何解决这个问题。 这是控制台中的错误
client.js?06a0:103 SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at Store.initializeStore (index.js?9101:14)
at wrappedMutationHandler (vuex.esm.js?2f62:844)
at commitIterator (vuex.esm.js?2f62:466)
at Array.forEach (<anonymous>)
at eval (vuex.esm.js?2f62:465)
at Store._withCommit (vuex.esm.js?2f62:624)
at Store.commit (vuex.esm.js?2f62:464)
at Store.boundCommit [as commit] (vuex.esm.js?2f62:409)
at VueComponent.mounted (default.vue?ec86:82)
这是我尝试使用 localStorage 的 store.js
export const state = () => ({
cart:{
items:[],
},
isAuthenticated: false,
token: '',
isLoading: false,
})
export const mutations = {
initializeStore(state) {
if (localStorage.getItem('cart')) {
state.cart = JSON.parse(localStorage.getItem('cart'))
} else {
localStorage.setItem('cart', JSON.stringify(state.cart))
}
},
addToCart(state, item) {
const exists = state.cart.items.filter(i => i.product.id === item.product.id)
if (exists.length) {
exists[0].quantity = parseInt(exists[0].quantity) + parseInt(item.quantity)
} else {
state.cart.items.push(item)
}
localStorage.setItem('cart', JSON.stringify(state.cart))
},
}
export const actions = {
}
这是我试图从 vuex 访问 localStorage 的 default.vue
export default {
data(){
return{
title:'QL Gadgets',
cart:{
items:[]
},
}
},
mounted(){
this.$store.commit('initializeStore')
},
computed:{
cartTotalLenght(){
let totalLenght = 0
for(let i=0; i < this.cart.items.length; i++){
totalLenght += this.cart.items[i].quantity
}
return totalLenght
}
},
methods:{
handleClick(){
if(this.$refs.menu.classList.contains('hidden')){
this.$refs.menu.classList.remove('hidden')
}
else{
this.$refs.menu.classList.add('hidden')
}
}
},
}
【问题讨论】:
标签: javascript vue.js nuxt.js vuex