The forEach method in Vuex's getters returns a single value instead of multiple values
P粉904191507
P粉904191507 2024-03-31 23:43:14
0
1
463

I have a shopping cart which is an array of products and I want to access each name in the cart. I have a forEach function in getters but it only returns a name. I tried .map() but it returns another array and I need multiple string values. can you help?

let cart = window.localStorage.getItem('cart')

const store = createStore({
    state: {
        
        cart: cart ? JSON.parse(cart) : [],
        

    },


 getters: {
   setTitle: state =>{
           let oneItem=''
            state.cart.forEach((item)=>{
                oneItem=item.ropeTitle
            })

            return oneItem
        },
}
}

P粉904191507
P粉904191507

reply all(1)
P粉792026467

This is because you only returned oneItem (let me guess, it was also the last item in the state.cart array?)

You can try using .join() to join the items together.

Suppose you want to use , to connect projects, you can try

setTitle: state => state.cart.map(item => item.ropeTitle).join(', ')
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template