search

Home  >  Q&A  >  body text

The forEach method in Vuex's getters returns a single value instead of multiple values

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粉904191507P粉904191507264 days ago500

reply all(1)I'll reply

  • P粉792026467

    P粉7920264672024-04-01 10:31:41

    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(', ')
    

    reply
    0
  • Cancelreply