IT이야기

인덱스에서 스플라이싱되지 않은 스플라이스는?

cyworld 2022. 5. 11. 22:06
반응형

인덱스에서 스플라이싱되지 않은 스플라이스는?

여기 바닐라 js 문제일 수도 있지만 특히 vuex에서 일하고 있다.상품 리스트에서 쇼핑카트로 버튼을 누르는 카트 설정이 있는데, 카트에서 삭제는 안 되네.여기 내 접근법이 있다.

버튼에서 동작을 호출하는 아이;

<b-button @click="removeItem" variant="primary">Remove from Cart</b-button>

data() {
    return {
        singleCart: this.items,
    };
},
methods: {
    removeItem() {
        this.$store.dispatch("DELETE_CART_ITEM", this.singleCart.item_id);
    },
},

그리고 내 vuex 상점에 있는 논리.

const actions = {
    ADD_TO_CART: (context, payload) => {
        context.commit('MUTATE_CART', payload)
    },
    DELETE_CART_ITEM: (context, payload) => {
        context.commit('DELETE_FROM_CART', payload)
    }
}

const mutations = {
    MUTATE_CART: (state, item) => {
        state.cart.push(item)
    },
    DELETE_FROM_CART: (state, payload) => {
        //filter the array for the item id, then splice it?

        console.log(payload)

        var index = state.cart.findIndex(item => item.item_id === payload)

        console.log(index)

        console.log(typeof index)

        state.cart.splice(index, 1)
    }
}

나의 모든 로깅은 정확한 페이로드와 카트에 있는 항목의 정확한 인덱스를 보여주지만 스플라이싱이 일어나면 시작 인덱스를 통과했음에도 불구하고 목록의 마지막 항목을 제거하는 것이다.

예를 들어 카트에 3개의 항목이 있고 두 번째 항목을 제거하려는 경우 적절한 인덱스를 찾아서 1개, 이 경우 1개가 로그에 기록되고 어떤 이유로든 목록의 마지막 항목이 삭제된다. 왜?그리고 내가 이걸 고치려면 어떻게 해야 하지?

해결책: 결국 내가 게터 데이터를 어떻게 불러야 할지 혼란스러웠다는 것이 밝혀졌는데, 해결책은 쇼핑 카트 항목을 반복하고 대신 계산된 속성을 사용하여 그렇게 얻는 상위 구성 요소에 있었다.

<div v-for="item in cart" :key="item.id">
<cartProduct :items="item" />
</div>

computed: {
    cart() {
        return this.$store.getters.GET_CART 
    }
},

그래서 반응적이었습니다.

이것은 이상한 Vue 주의사항이다.아래는 이 경우에 효과가 없는 것의 예다.

DELETE_FROM_CART: (state, payload) => {
        var index = state.cart.findIndex(item => item.item_id === payload);
        var dummy = state.cart.slice();
        dummy.splice(index, 1);
        state.cart = dummy;
    }

참조URL: https://stackoverflow.com/questions/64450630/splice-not-splicing-from-the-index-its-being-given

반응형