localStorage를 이용한 장바구니 구현

sdsdsrd·2020년 11월 15일
0

졸업프로젝트

목록 보기
13/15

localStorage에 key값을 숫자로 하여 장바구니 메뉴들을 저장할 것이다.

1. 장바구니에 담기

@/menu/MenuDetailPage.vue

let index = 0; //새로운 메뉴가 들어갈 index (maxIndex + 1)
var isSame = false; //중복되는 메뉴가 있는지
var price = 0;
var count = 0;
if (localStorage.length > 0) {
  for (let i = 0; i < localStorage.length; i++) {
    if (Number(index) < Number(localStorage.key(i))) { //maxIndex 구하기
      index = localStorage.key(i);
      var cartItem = JSON.parse(localStorage.getItem(localStorage.key(i)));
      if ( //menu와 option이 같으면 같은 메뉴이므로 price와 count만 바꿔준다
        JSON.stringify(cartItem.menu) == JSON.stringify(menu) &&
        JSON.stringify(cartItem.option) == JSON.stringify(option)
      ) {
        isSame = true;
        price = cartItem.price;
        count = cartItem.count;
        break;
      }
    }
  }
}
if (isSame == true) { //중복되는 물건이 장바구니에 있는 경우 price와 count만 바꿔준다
  var value = {
    id: index,
    menu: menu,
    option: option,
    price: this.price + price,
    count: this.count + count,
  };
} else { //새로운 메뉴인 경우 maxIndex + 1을 key로 하여 저장한다
  index = Number(index) + 1;
  value = {
    id: index,
    menu: menu,
    option: option,
    price: this.price,
    count: this.count,
  };
}

localStorage.setItem(index, JSON.stringify(value)); //localStorage에 저장

2. 장바구니 메뉴 불러오기

@/order/CartPage.vue

export default {
  data() {
    return {
      store: '',
      cartItems: [],
      totalPrice: 0,
    };
  },
  created() {
    this.store = localStorage.getItem('store');
    if (localStorage.length > 0) {
      for (let i = 0; i < localStorage.length; i++) {
        if ( //key가 숫자인 것들만 장바구니 메뉴임
          localStorage.key(i) !== 'loglevel:webpack-dev-server' &&
          localStorage.key(i) !== 'store-id' &&
          localStorage.key(i) !== 'store' &&
          localStorage.key(i) !== 'nearest-store-id' &&
          localStorage.key(i) !== 'nearest-store'
        ) {
          //string 형식을 json 형식으로 바꿔서 cartItems에 넣어준다.
          this.cartItems.push(JSON.parse(localStorage.getItem(localStorage.key(i))));
        }
      }
    }
    for (let i = 0; i < this.cartItems.length; i++) {
      this.totalPrice += this.cartItems[i].price;
    }
  },
  ...
};

0개의 댓글