롤 전적 사이트 구현 - 페이징, 정렬 (front)

essential·2023년 9월 6일
0

op.gg

목록 보기
14/16

Templete(HTML)

<template>
  <div class="board-list">
    <div class="common-buttons">
      <button
        type="button"
        class="w3-button w3-round w3-blue"
        @click="handleWrite"
      >
        등록
      </button>
    </div>
    <table class="w3-table-all">
      <thead>
        <tr>
          <th @click="sort('bno')">No</th>
          <th @click="sort('title')">제목</th>
          <th @click="sort('id')">작성자</th>
          <th @click="sort('created_date')">등록일</th>
          <th @click="sort('updated_date')">수정일</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row, bno) in lists" :key="bno">
          <td>{{ row.bno }}</td>
          <td>
            <router-link :to="`/board/${row.bno}`">{{ row.title }}</router-link>
          </td>

          <td>{{ row.id }}</td>
          <td>{{ row.created_date }}</td>
          <td>{{ row.updated_date }}</td>
        </tr>
      </tbody>
    </table>
  </div>
   <div class="pagination">
    <button
      v-if="sortPg.current_page > 1"
      class="prev w3-button w3-border"
      @click="changePage(sortPg.current_page - 1)"
    >
      이전
    </button>

    <button
      v-for="(n, index) in displayedPages"
      :key="index"
      :class="[
        'w3-button',
        'w3-border',
        pagination.current_page === n ? 'w3-green' : '',
      ]"
      @click="changePage(n)"
    >
      {{ n }}
    </button>

    <button
      v-if="sortPg.current_page < pagination.total_pages"
      class="next w3-button w3-border"
      @click="changePage(sortPg.current_page + 1)"
    >
      다음
    </button>
  </div>
</template>

BoardList에서 sort 이벤트 추가, page 이동 이벤트를 추가하는게 생각보다 엄청 번거로웠다.
이거 쓰면서 생각나서 이전, 다음 버튼 잘 되나 보니까 안 된다. 진짜 개소름끼친다... 한 번에 잘 되는게 없어!!!!


Script

<script>
import { mapState } from "vuex";

export default {
  data() {},
  created() {
    this.getList();
  },
  computed: {
    ...mapState({
      lists: (state) => state.board.lists,
      pagination: (state) => state.board.pagination,
    }),
    displayedPages() {
      let pages = [];
      for (
        let i = this.pagination.start_page;
        i <= this.pagination.end_page;
        i++
      ) {
        pages.push(i);
      }
      return pages;
    },
  },
  methods: {
    handleWrite() {
      this.$router.push("/board/write");
    },
    getList() {
      this.$store.dispatch("getBoardList");
    },
     changePage(page) {
      this.$store.commit("setSortPg", {
        current_page: page,
        sort_by: this.sortPg.sort_by,
        order: this.sortPg.order,
      });
      this.getList();
    },
    sort(item) {
      this.order = this.order === "asc" ? "desc" : "asc";
      this.$store.commit("setSortPg", {
        current_page: 1,
        sort_by: item,
        order: this.order,
      });
      this.getList();
    },
  },
};
</script>

위에 Templete 랑 Script 에서

    <button
      class="prev w3-button w3-border"
      @click="changePage(current_page - 1)"

      이전
    </button>
    changePage(page) {
      this.$store.commit("setSortPg", {
        current_page: page,
        sort_by: "",
        order: "",
      });
      this.getList(); // 페이지가 바뀔 때마다 게시글 목록을 새로 불러옴
    },

이 두 코드들이 뭔가 문제가 있다.

F12 > networt 보니까 current_page 에 값이 안 들어간다. 되는 게 뭘까? 이제 나도 모르겠다.. 밥 먹고 와서 고쳐야지...


BoardStore

import axios from "axios";

const state = {
  lists: [],
  details: {
    bno: "",
    id: "",
    title: "",
    content: "",
    viewcount: "",
    created_date: "",
    updated_date: "",
    fno: "",
    org_file: "",
    stored_file: [],
    group_file: "",
  },
  posts: {
    title: "",
    content: "",
    org_file: [],
  },
  sortPg: {
    current_page: 1,
    page_size: 5,
    sort_by: "bno",
    order: "asc",
  },
  pagination: {
    current_page: "",
    start_page: "",
    end_page: "",
    total_pages: "",
  },
};

const mutations = {
  setLists(state, data) {
    state.lists = data;
  },
  setDetails(state, data) {
    state.details = data;
    state.details.stored_file = data.fileList.map((file) => file.stored_file);
  },
  setPosts(state, data) {
    state.posts = data;
  },
  setPagination(state, data) {
    state.pagination = data;
  },
  setSortPg(state, data) {
    state.sortPg = data;
  },
};

const actions = {
    getBoardList(context) {
      // 글 목록
      axios
        .get("/api/board/list", { params: context.state.sortPg })
        .then((res) => {
          console.log("API 호출 성공", res.data);
          context.commit("setLists", res.data.lists);
          context.commit("setPagination", res.data.pagination);
          console.log("test", state.pagination);
        })
        .catch((e) => {
          console.error("API 호출 실패", e);
        });
    },
  };
  
  
export default {
  state,
  getters,
  mutations,
  actions,
};

원래 호출하는 코드가 10000개 정도 있는데 너무 길어서 글 목록 부분만 가져왔다. 내 코드가 좀 맘에 안 들었던 게 뭐냐면

context.commit("setLists", res.data.lists);
context.commit("setPagination", res.data.pagination);

이딴 식으로 값 두 번 저장하는 거...

ㅋㅋ 대체 왜 저렇게 했냐면... state 를 나눌 수 밖에 없었다....
pagination, sortPg 이렇게 나눠야 호출할 때 sortPg 를 보내고 서버에서 pagination (실제로 페이징을 할 수 있게 하는 데이터들) 을 받아와야 했다. 그리고 빈 문자열로 초기화 하고 있기 때문에 typerror 도 남... 어쩔 수 없었다고 정신승리중. 그래도 뭔가... 한 번에 두 개의 state 의 상태를 변경할 수 있지 않을까? 싶긴 한데 모르겠다 시간 남으면 해야지.


페이지 이전, 다음 버튼 수정하기~! (09.06 까지)
수정했다~~

@click="changePage(sortPg.current_page - 1)"

여기서 sortPg < 이것만 추가했다 원래는 current_page 였는데 아마 pagination 이랑 sortPg 둘다 current_page 가 있어서 NaN 을 반환한 것 같다

  changePage(page) {
      this.$store.commit("setSortPg", {
        current_page: page,
        sort_by: this.sortPg.sort_by,
        order: this.sortPg.order,
      });
      this.getList();
    },

이것도 수정함~ 정렬한 상태로 페이지 이동을하면 정렬이 원래대로 바뀌는 기적같은 일이 일어나서ㅋㅋ 보니까 "" 으로 되어있길래 state 를 가져오도록 했다.


수정을 한다면 좀 헷갈리는 pagination, sortPg의 current_page 를 가져오는 부분을 좀 통일하고 싶다. 왜냐면 다 다른 current_page 쓰는 중... 마음이 불편하다...
그리고 사수님한테 여쭤봤는데 페이지의 끝

  • 페이지가 6개면 123...6 이런식?

을 보여주는 것도 추가 해야한다. 이건 라이엇 api 구현 다 하면 하는 걸로~
아니면 << >> 버튼을 누르면 페이지의 시작과 끝으로 이동하는 것도 좋을 것 같다.

profile
essential

0개의 댓글