[to do list] 페이지네이션 구현

youngseo·2022년 3월 1일
1

JS프로젝트

목록 보기
8/18
post-thumbnail

To-do-list에 페이지네이션 구축하기

Json server의 Router 중 하나인 Peginats기능을 이용해 페이지 네이션을 구축해볼 예정입니다.

페이지네이션 구축전후

1. 페이지네이션 설정값

실제 현업에서 페이지네이션을 구현하는 경우, 데이터를 가져올 때 총 데이터가 몇개인지를 함께 반환해줍니다.

하지만 JSON-server의 경우 그 값을 같이 주지 않기 때문에 임의로 totalCount를 53으로 설정을 했습니다.

  let currentPage = 1
  const totalCount = 53
  const pageCount = 5
  const limit = 5

2. piginats 설정

2-1 peginats라우터

GET /posts?_page=7  //7번째 페이지를 불러옴
GET /posts?_page=7&_limit=20 // 20개씩 잘린 데이터에서 7번째 페이지를 가져옴, limit이 없는 경우 10개씩

2-2 프로젝트에 적용

  const getTodos = () => {
    fetch(`${API_URL}?_page=${currentPage}&_limit=${limit}`)
      .then((response) => response.json())
      .then((todos) => {
        renderAllTodos(todos)
      })
      .catch((error) => console.error(error.message))
  }

3. 페이징 처리

3-1. pagination함수 생성 및 DOM연결

  const $pagination = get('.pagination')


  const pagination = () => {
    let totalPage = Math.ceil(totalCount / limit)
    let pageGroup = Math.ceil(currentPage / pageCount)

    //마지막 숫자 구하기
    let lastNumber = pageGroup * pageCount
    if (lastNumber > totalPage) {
      lastNumber = totalPage
    }
    //첫번째 숫자 구하기
    let firstNumber = lastNumber - (pageCount - 1)    

    const next = lastNumber + 1
    const prev = firstNumber - 1
  }

3-2. pagination함수 호출

로딩하는 시점에 pagination함수를 호출 해줍니다.

    window.addEventListener('DOMContentLoaded', () => {
      getTodos()
      pagination()
    })

3-3 HTML작성

html변수를 하나 만들어 로직을 작성한 후 index.htmlpagination클래스에 뿌려주도록 하겠습니다.

  const pagination = () => {
    ...

    let html = ''

    if(prev > 0){
      html += "<button class='prev' data-fn='prev'>이전</button>"
    }

    $pagination.innerHTML = html
  }

3-4 숫자렌더링

  const pagination = () => {
    ...
    
    for( let i = firstNumber; i <= lastNumber; i++){
      html += `<button class='pageNumber' id='page_${i}'>${i}</button>`
    }
    
    if (lastNumber < totalPage) {
      html += `<button class='next' data-fn='next'>다음</button>`
    }
  }

3-5 현재페이지 표시

스타일을 변경하여 현재 페이지를 표시합니다.

  const pagination = () => {
    ...
    
    const $currentPageNumber = get(`.pageNumber#page_${currentPage}`)//id로 몇번째 페이지인지 알아냄
    $currentPageNumber.style.color = '#9dc0e9'
  }

3-6 클릭 이벤트 구현

    const $currentPageNumbers = document.querySelectorAll('.pagination button')
    $currentPageNumbers.forEach(button => {
      button.addEventListener('click', () => {
        if (button.dataset.fn === 'prev') {
          currentPage = prev
        } else if (button.dataset.fn === 'next') {
          currentPage = next
        } else {
          currentPage = button.innerText //i
        }
        pagination()
        getTodos()
      })
    })
  }

0개의 댓글