본문 바로가기

코딩애플/코딩애플-vue.js

[16] sort 함수

[16] 상품정렬기능과 데이터 원본 보존

 

원룸들 데이터를 가격으로 정렬하면 알아서 노출되겠지??

 

 

 

{{데이터 바인딩}}을 해두면 HTML에 데이터가 실시간으로 반영

 

 

 

sort() 설명

a-b =음수면  a는 왼쪽
2 - 5 = -3
App.vue

import { apple, data } from "./assets/oneroom.js"; // import

data() {
    return {
      누른거: 0,
      원룸들: data, // 데이터
      모달창열렸니: false,
      신고수: [0, 0, 0],
      menus: ["Home", "Shop", "About"],
      products: ["역삼동 원룸", "천호동 원룸", "마포구 원룸"],
      prices: [70, 60, 50],
      logo: "로고샵",
      스타일: "color : red",
      profileUrl: [
        require("./assets/room0.jpg"),
        require("./assets/room1.jpg"),
        require("./assets/room2.jpg"),
      ],
    };
  },
methods: {
    increase(i) {
      this.신고수[i] += 1;
    },
    priceSort() {
      this.원룸들.sort(function (a, b) { // 데이터 사용
        return a.price - b.price;
      });
    },
  },
  
  
  Modal.vue
  
     <Modal
      @closeModal="모달창열렸니 = false"
      :원룸들="원룸들" // 데이터 사용
      :누른거="누른거"
      :모달창열렸니="모달창열렸니"
      :신고수="신고수"
    />
    
    
    
     <p>{{ 원룸들[누른거].content }}</p>

 

oneroom.js

var data =
    [
        {
            id: 0,
            title: "Sinrim station 30 meters away",
            image: "https://codingapple1.github.io/vue/room0.jpg",
            content: "18년 신축공사한 남향 원룸 ☀️, 공기청정기 제공",
            price: 340000
        },
        {
            id: 1,
            title: "Changdong Aurora Bedroom(Queen-size)",
            image: "https://codingapple1.github.io/vue/room1.jpg",
            content: "침실만 따로 있는 공용 셰어하우스입니다. 최대 2인 가능",
            price: 450000
        },
        {
            id: 2,
            title: "Geumsan Apartment Flat",
            image: "https://codingapple1.github.io/vue/room2.jpg",
            content: "금산오거리 역세권 아파트입니다. 애완동물 불가능 ?",
            price: 780000
        },
        {
            id: 3,
            title: "Double styled beds Studio Apt",
            image: "https://codingapple1.github.io/vue/room3.jpg",
            content: "무암동인근 2인용 원룸입니다. 전세 전환가능",
            price: 550000
        }
   ];
        
  export { apple, data }

 

 

 

 

sort 사용

App.vue

<template>
  {{ logo }}
  <div class="menu">
    <a v-for="menu in menus" :key="menu">{{ menu }}</a>
  </div>

  <Discount />

  <button @click="priceSort">가격 순 정렬</button>

  <transition name="fade">
    <Modal
      @closeModal="모달창열렸니 = false"
      :원룸들="원룸들"
      :누른거="누른거"
      :모달창열렸니="모달창열렸니"
      :신고수="신고수"
    />
  </transition>

  <Product
    @openModal="
      모달창열렸니 = true;
      누른거 = $event;
    "
    :원룸="원룸들[i]"
    v-for="(작명, i) in 원룸들"
    :key="작명"
  />

  <!-- <div v-for="(product, i) in 원룸들" :key="product">
    <img :src="product.image" class="room-img" />
    {{ product.image }}
    <h4
      class="red"
      :style="스타일"
      @click="
        모달창열렸니 = true;
        누른거 = i;
      "
    >
      {{ product.title }}
    </h4>
    <p>{{ product.price }} 만원</p>
    <button @click="increase(i)">허위 매물 신고</button>
    <span>신고 수: {{ 신고수[i] }}</span>
  </div> -->
</template>

<script>
//데이터 바인딩.. js데이터를 Html에 꽂아넣음
import { apple, data } from "./assets/oneroom.js";
import Discount from "./Discount.vue";
import Modal from "./Modal.vue";
import Product from "./Product.vue";
console.log("apple>>>> ", apple);

export default {
  name: "App",
  data() {
    return {
      누른거: 0,
      원룸들: data,
      모달창열렸니: false,
      신고수: [0, 0, 0],
      menus: ["Home", "Shop", "About"],
      products: ["역삼동 원룸", "천호동 원룸", "마포구 원룸"],
      prices: [70, 60, 50],
      logo: "로고샵",
      스타일: "color : red",
      profileUrl: [
        require("./assets/room0.jpg"),
        require("./assets/room1.jpg"),
        require("./assets/room2.jpg"),
      ],
    };
  },
  methods: {
    increase(i) {
      this.신고수[i] += 1;
    },
    priceSort() {
      this.원룸들.sort(function (a, b) {
        return a.price - b.price;
      });
    },
  },
  components: {
    Discount: Discount,
    Modal: Modal,
    Product: Product,
  },
};
</script>

<style>
.start {
  opacity: 0;
  transition: all 1s;
}
.end {
  opacity: 1;
}
.fade-enter-from {
  opacity: 0;
  transform: translateY(100px);
}
.fade-enter-active {
  transition: all 1s;
}
.fade-enter-to {
  opacity: 1;
}

.fade-leave-from {
  opacity: 1;
}
.fade-leave-active {
  transition: all 1s;
}
.fade-leave-to {
  opacity: 0;
}

.room-img {
  width: 100%;
  margin-top: 40px;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.menu {
  background: darkslateblue;
  padding: 15px;
  border-radius: 5px;
}
.menu a {
  color: white;
  padding: 10px;
}
body {
  margin: 0;
}
div {
  box-sizing: border-box;
}
.black-bg {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  position: fixed;
  padding: 20px;
}
.white-bg {
  width: 100%;
  background: beige;
  border-radius: 8px;
  padding: 20px;
}
</style>

 

점 3개 ... 문법 (spread operator) 에 대한 내용

. . . 이 기호는 spread operator 라는 신기한 문법인데

array나 object 앞에 붙일 수 있으며 

array, object의 괄호를 제거해주는 문법입니다. 

그래서 . . . [1,2,3] 이런 식으로 쓰면 1,2,3만 남는다는 소리입니다. 

 

그래서 약간의 트릭인데 array를 복사할 때 spread operator 이걸로 괄호를 벗겼다가 다시 씌우면 

그런 값공유 현상이 일어나지않게 복사할 수 있습니다. 

array를 해체했다가 다시 array로 만들면 서로 값 공유하지않는 별개의 사본을 만들 수 있어서 그렇습니다.

일종의 편법입니다.

 

숙제

1. 상품명 가나다순 정렬

https://velog.io/@1106laura/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EB%AC%B8%EC%9E%90%EC%97%B4-%EC%88%AB%EC%9E%90-%EC%A0%95%EB%A0%AC%ED%95%98%EA%B8%B0

titleSort() {
      this.원룸들.sort(function (a, b) {
        if (a.title < b.title) return -1;
        else if (a.title > b.title) return 1;
        else if (a.title === b.title) return 0;
        else return -1;
      });
    },

 

2. 가격 역순 정렬

priceSortReverse() {
      this.원룸들.sort(function (a, b) {
        return b.price - a.price;
      });
    },

 

3. 50만원 이하의 상품만 보여주는 필터

filterPrice() {
      this.원룸들 = this.원룸들.filter((val) => {
        return val.price < 500000;
      });
    },

'코딩애플 > 코딩애플-vue.js' 카테고리의 다른 글

[part2-5] Nested routes & push 함수  (0) 2022.01.10
[17] lifecycle hooks  (0) 2022.01.04
[15] vue 애니메이션  (0) 2022.01.04
[14] watcher  (0) 2022.01.03
[13] v-model  (0) 2022.01.03