programing

Vuex는 내부 첫 번째 행의 버튼을 클릭할 때만 컴포넌트를 갱신합니다.

yoursource 2022. 8. 13. 12:40
반응형

Vuex는 내부 첫 번째 행의 버튼을 클릭할 때만 컴포넌트를 갱신합니다.

나는 Vuex와 장난치고 있고, 거의 작동되고 있다. 단지 이 문제가 나를 괴롭히고 있다.제품 리스트가 있습니다.각 제품마다 클릭 시 "add To Cart()" 이벤트가 있습니다.

제품이 카트에 추가되면 홈에서 카트를 업데이트합니다.vue 컴포넌트이상하게도 첫 번째 제품의 addToCart 버튼을 클릭하거나 두 번째 제품의 버튼을 처음 사용할 때만 업데이트가 됩니다.첫 번째 제품의 버튼을 클릭해야만 두 제품의 수량이 업데이트됩니다.

이것이 내 코드이고, 이것이 Home 컴포넌트입니다.vue:

<template>
  <div class="home">
    <div v-for="product in cart" :key="product.id">
      {{product.name}} {{product.quantity}}
    </div>
    <div v-for="product in products" :key="product.id">
        {{product.name}}
        <button @click="addToCart(product)">Add to cart</button>
    </div>
  </div>
</template>

<script>
export default {
  /* eslint-disable */
  name: 'Home',
  data () {
    return {
      products: [
        {
          id: 1,
          name: 'Appeltaart',
          price: '20.00'
        },
        {
          id: 2,
          name: 'Chocoladetaart',
          price: '15.40'
        }
      ],
    }
  },
  computed: {
    cart() {
      return this.$store.getters.cart
    }
  },
  beforeMount() {
  },
  methods: {
    addToCart(product) {
      this.$store.commit('addToCart', product)
    },
  }
}
</script>

마지막으로 Index.js라는 Vuex 파일을 보여 줍니다.

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  /* eslint-disable */
  state: {
    cart: [],
    newCartItem: {
      id: 0,
      name: '',
      price: 0,
      quantity: 0,
    },
  },
  mutations: {
    addToCart (state, product) {
      console.log(state.cart)
      let findProduct = state.cart.find(o => o.id === product.id)
      if ( findProduct ) {
          findProduct.quantity += 1;
      } else {
          state.newCartItem.id = product.id
          state.newCartItem.name = product.name;
          state.newCartItem.price = product.price;
          state.newCartItem.quantity = 1;
          state.cart.push(state.newCartItem)
          state.newCartItem = {}
      }
    }
  },
  actions: {
  },
  modules: {
  },
  getters: {
    cart: state => state.cart
  }
})

첫 번째 제품의 addToCart를 클릭해도 다음 오류가 발생합니다.

[Vue warn]: Duplicate keys detected: '1'. This may cause an update error.
[Vue warn]: Duplicate keys detected: '2'. This may cause an update error.

편집 첫 번째 제품뿐만 아니라 클릭하는 두 번째 제품의 addToCart도 항상 해당됩니다.

UPDATE 중복 키 문제 수정

교환을 시도하다state.cart.push(state.newCartItem)타고state.cart.push(Object.assign({},state.newCartItem))당신의 가게에서

관찰자가 제대로 작동할 수 있는 상태에 놓이게 될 것이다.

카트는

0: {__ob__: Observer}
1: {__ob__: Observer}

대신

0: {__ob__: Observer}
1: {id: 2, name: "Chocoladetaart", price: "15.40", quantity: 2, __ob__: Observer}

언급URL : https://stackoverflow.com/questions/68291609/vuex-only-updating-component-when-clicking-on-the-button-of-the-first-row-inside

반응형