1. 데이터 가공
1) 페이지가 로드될 때 서버에서 데이터를 받아 옴
created(){
getAllData()
}
methods: {
async getAllData(){
try{
const response = await axios.post(`${this.baseUrl}/api/data`, {
opt: 'all' //통신에 필요한 파라미터
})
console.log('데이터 조회 응답: ', response)
this.allData = response.data
this.data1 = response.data
} catch(error){
console.error('데이터 조회 오류: ', error)
alert('데이터 조회 중 오류 발생')
}
}
}
2) 데이터 가공
data1 변경됨 → watch 실행
watch:{
data1(){
this.currentPage = 1
}
}
currentPage 변경됨 → computed 속성 계산됨
computed: {
totalPages(){
return Math.cell(this.data1.length / this.itemsPerPage)
},
paginatedData(){
const start = (this.currentPage -1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.data1.slice(start, end)
},
displayedPages(){
const range = 5 //한 번에 보여줄 페이지 번호 개수
let start = Math.max(1, this.currentPage - Math.floor(range/2))
let end = Math.min(this.totalPages, start + range - 1)
//start 조정
if(end === this.totalPages){
start Math.max(1, end - range + 1)
}
//페이지 번호 배열 생성
const pages = []
for(let i = start; i <= end; i++){
pages.push(i)
}
return pages
}
}
2. 데이터 출력
computed된 paginatedData를 기반으로 데이터 행이 렌더링됨
<tr v-for="data11 in paginatedData" :key="data.dataname">
<td>{{ data.dataname }}</td>
</tr>
3. 페이지 넘기기
<!-- 페이징 컨트롤 -->
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1"
class="page-btn"
>이전</button>
<button
v-for="pageNum in displayedPages"
:key="pageNum"
@click="currentPage = pageNum"
:class="['page-btn', {active: currentPage === pageNum}]"
>
{{ pageNum }}
</button>
<button
@click="currentPage++"
:disabled="currentPage === totalPages"
class="page-btn"
>다음</button>
</div>
1) 이전 버튼
① @click="currentPage--"
클릭시 currentPage 변수 1 차감
② currentPage의 값이 1인 경우 disabled
2) 다음 버튼
① @click="currentPage++"
클릭시 currentPage 변수 2 가산
② currentPage의 값이 totalPages의 값과 같은 경우 disabled
3) 페이지 숫자 목록
① v-for="pageNum in displayedPages"
computed 속성 displayedPages에서 반환한 값을 pageNum이라는 변수로 순회
② @click="currentPage = pageNum"
클릭시 currentPage의 값을 pageNum으로 설정
③ class="['page-btn', {active: currentPage === pageNum}]"
currentPage의 값이 pageNum과 같은 경우 클래스에 active 추가
페이징 컨트롤의 요소를 클릭하면 currentPage의 값이 변화하고, 이에 따라 computed의 pagenatedUsers()가 실행되어 화면에 표시되는 값이 변경됨.
'vue.js' 카테고리의 다른 글
[vue] ref란? (0) | 2025.02.25 |
---|---|
[Vue] 기초 응용 key-value 객체 (0) | 2025.02.18 |
[vue.js] Vuex (0) | 2025.01.09 |
[vue.js] Reusability & Composition (0) | 2025.01.08 |
[vue.js] 컴포넌트 심화 (0) | 2025.01.08 |