Vue.js에서 테이블을 정렬할 때, 사용자가 클릭한 정렬 기준(column)과 정렬 방향(오름차순/내림차순)을 새로고침해도 그대로 유지시키고 싶을 때가 많습니다. 이럴 때 가장 깔끔하고 강력한 방법은 바로 URL 쿼리(query string)를 활용하는 것입니다.
📌 목차
- 왜 URL 쿼리를 사용할까?
- 정렬 상태를 URL에 반영하기
- created() 훅에서 초기값 읽기
- computed로 정렬된 목록 반환
- 정렬 버튼 클릭 시 처리 로직
- 기본 정렬로 되돌리기
1. 왜 URL 쿼리를 사용할까?
사용자가 데이터를 정렬한 상태 그대로 새로고침하거나 URL을 공유할 수 있게 하려면 URL 쿼리가 적절한 수단입니다. 세션 저장소나 Vuex 없이도 this.$route.query만으로 충분히 구현 가능합니다.
2. 정렬 상태를 URL에 반영하기
예: ?sortColumn=price&sortDirection=asc 아래는 정렬 조건을 클릭할 때마다 쿼리로 반영하는 코드입니다.
setSort(columnKey) {
if (this.sortColumn === columnKey) {
// 같은 컬럼 클릭 시 정렬 방향 토글
this.sortDirection = this.sortDirection === "asc" ? "desc" : "asc";
} else {
// 새로운 컬럼 클릭 시 기본 방향은 desc
this.sortColumn = columnKey;
this.sortDirection = "desc";
}
this.$router.replace({
query: {
...this.$route.query,
sortColumn: this.sortColumn,
sortDirection: this.sortDirection,
},
});
}
3. created() 훅에서 초기값 읽기
페이지 진입 시 쿼리 파라미터를 기반으로 정렬 기준을 세팅합니다.
created() {
const { sortColumn, sortDirection } = this.$route.query;
const validColumns = ["name", "price", "rating"];
const validDirections = ["asc", "desc"];
if (validColumns.includes(sortColumn)) {
this.sortColumn = sortColumn;
}
if (validDirections.includes(sortDirection)) {
this.sortDirection = sortDirection;
}
}
4. computed로 정렬된 목록 반환
아래는 상품 목록 예시입니다. 기본 정렬은 서버에서 `desc`로 내려오고, asc로 바꾸고 싶을 때만 reverse()를 합니다.
computed: {
sortedProductList() {
const rawList = this.productData[this.sortColumn];
if (!rawList || rawList.length === 0) return [];
let result = [...rawList];
if (this.sortDirection === "asc") {
result.reverse(); // 서버에서 이미 desc 정렬된 데이터 기준
}
return result.slice(0, 5); // 예시로 상위 5개만 사용
},
}
5. 정렬 버튼 클릭 시 처리 로직
<th @click="setSort('price')" style="cursor: pointer">
가격
<img
:src="sortColumn === 'price' && sortDirection === 'desc' ? downArrow : ''"
style="margin-left: 4px"
/>
</th>
이런 식으로 컬럼별로 sortColumn과 sortDirection을 조건으로 아이콘도 표시할 수 있습니다.
6. 기본 정렬로 되돌리기
동일한 컬럼을 다시 클릭했을 때 초기값으로 되돌리는 방식입니다.
setSort(columnKey) {
if (this.sortColumn === columnKey) {
if (this.sortDirection === "desc") {
// 같은 컬럼에서 desc면 초기값으로 리셋
this.sortColumn = "rating";
this.sortDirection = "desc";
} else {
this.sortDirection = "desc";
}
} else {
this.sortColumn = columnKey;
this.sortDirection = "desc";
}
this.$router.replace({
query: {
...this.$route.query,
sortColumn: this.sortColumn,
sortDirection: this.sortDirection,
},
});
}
📝 마무리
Vue.js에서 URL 쿼리를 활용하면 사용자가 보고 있는 데이터를 어떤 기준으로 정렬했는지 기억할 수 있어 UX가 대폭 향상됩니다. 검색, 정렬, 필터링 같은 UI에서는 반드시 적용해보세요.
'개발' 카테고리의 다른 글
| 왜 브라우저는 HTTPS가 되는데 Java 서버는 실패할까? (0) | 2025.09.16 |
|---|---|
| React + Capacitor로 안드로이드 앱 실행하기 (Android Studio) (1) | 2025.07.30 |
| CORS 정책 정리: 웹 API 개발자가 꼭 알아야 할 개념 (Spring 기준) (0) | 2025.07.14 |
| Vue Firebase 배포 방법 (Vite 기반 실전 예제) (0) | 2025.07.14 |
| Spring Boot 애플리케이션을 Cloud Run에 Docker로 배포하기 (GCP 배포 실습) (2) | 2025.07.11 |