programing

vue에서 상태 항목을 채우는 방법

copyandpastes 2022. 7. 20. 22:53
반응형

vue에서 상태 항목을 채우는 방법

ID를 가진 카트가 있으며 cart_guid(carts/70290ee4-258b-11cb-9ca4-42ca64dfa778)로 전화를 걸면 json:

{
    "data": {
        "type": "carts",
        "id": "70290ee4-258b-11cb-9ca4-42ca64dfa778",
        "attributes": {
            "cart_guid": "70290ee4-258b-11cb-9ca4-42ca64dfa778",
            "total_price_excl_vat": 70,
            "total_vat": 66.5,
            "total_price_incl_vat": 136.5,
            "items": [
                {
                    "id": 300,
                    "cart_id": 663,
                    "product_id": "2021-05-07.1.1",
                    "product_name": "Product",
                    "product_short_description": "short description",
                    "product_image": "img",
                    "variation_id": 1,
                    "variation_name": "child",
                    "price_excl_vat": 10,
                    "vat_percentage": 0.95,
                    "amount": 7,
                    "created_at": "2021-10-26T11:29:31.000000Z",
                    "updated_at": "2021-10-26T11:30:02.000000Z"
                }
            ],
            "createdAt": "2021-10-26T11:29:09.000000Z",
            "updatedAt": "2021-10-26T11:30:02.000000Z"
        }
    }
}

그래서 새로 고쳤을 때 페이지 항목이 다시 비어 있어서 어떻게 채워야 할지 정말 혼란스럽습니다.그래서 내 상태:

export default {
    cart: {
        "attributes": {
            "items": [],
        }
    }
}

변환:

export const ADD_TO_CART = (state, {cart}) => {
    state.cart = cart;
}

및 액션:

export const addProductToCart = ({commit}, {cart}) => {
    commit('ADD_TO_CART', {cart});
}

덧붙여서 Add to Cart 버튼을 클릭하면 아이템을 채울 수 있습니다.로직은 다음과 같습니다.

addToCart: function () {
            this.amount = this.itemsCount !== "" ? this.itemsCount : 1;
            if(this.variationId != null) {
                this.warningMessage = false;
                cartHelper.addToCart(this.product.id, this.variationId, parseInt(this.amount), (response) => {
                    this.$store.dispatch('addProductToCart', {
                        cart: response.data,
                    })
                });
            } else {
                this.warningMessage = true;
            }
        },

나는 그것을 어떻게 달성해야 할지 매우 혼란스럽고 많은 코드를 알지만 당신이 나를 도와줄 수 있기를 바랍니다.마지막으로 cookieValue(cart_guis)가 카트를 호출하는지 확인했습니다.

checkCart: function(callback = undefined) {
        if(this.cookieValue != null) {
            this.getCart((response) => {
                if (callback) { callback(response); }

                console.log("cookie var")
            });
        } 
    },

또한 index.vue에서 다음을 마운트하려고 합니다.

mounted() {
        cartHelper.checkCart((response) => {
            if(response.data.attributes.item == null) {
                this.$store.dispatch('addProductToCart', {
                    cart: response.data,
                })
            }
        });
    },

여기에 이미지 설명 입력

사용하고 있다vuex-persistedstate좋은 선택이라고 생각합니다.여기서 찾을 수 있어요vuex-persistedstate가 말했듯이

페이지 새로고침 사이에 Vuex 상태를 유지 및 재하이드화합니다.

데이터는 브라우저의 로컬 스토리지에 저장되므로 간단하게 사용할 수 있습니다.아래에 예를 제시하겠습니다.

변환:

export const addToCart = (state, response) => {
  const findingItem = state.cart.findIndex(item => item.id === response.id);

  if (findingItem === -1) {
    state.cart.push(response);
  }
};

(반복하지 않도록 하기 위해)

index.disc : (스토어 컨피규정

import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';

import module1 from './module1';

Vue.use(Vuex);

const Store = new Vuex.Store({
  modules: {
    module1,
  },

  plugins: [createPersistedState()],
 
});

export default Store;

addToCart 함수:

  this.$store.commit('module1/addToBag', item, {
      module: 'module1',
    });

가방 표시:

created() {
    this.cart = this.$store.state.module1.cart;
  },

ps : 모듈러 방식의 스토어를 사용했습니다.

언급URL : https://stackoverflow.com/questions/69723839/how-to-fill-items-of-the-state-in-vue

반응형