본문 바로가기
개발

Vue.js에서 URL 쿼리로 테이블 정렬 상태 기억하기 - 새로고침에도 유지돼는 UX 만들기

by 새싹 아빠 2025. 7. 21.

Vue.js에서 테이블을 정렬할 때, 사용자가 클릭한 정렬 기준(column)정렬 방향(오름차순/내림차순)을 새로고침해도 그대로 유지시키고 싶을 때가 많습니다. 이럴 때 가장 깔끔하고 강력한 방법은 바로 URL 쿼리(query string)를 활용하는 것입니다.

📌 목차

  1. 왜 URL 쿼리를 사용할까?
  2. 정렬 상태를 URL에 반영하기
  3. created() 훅에서 초기값 읽기
  4. computed로 정렬된 목록 반환
  5. 정렬 버튼 클릭 시 처리 로직
  6. 기본 정렬로 되돌리기

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>

이런 식으로 컬럼별로 sortColumnsortDirection을 조건으로 아이콘도 표시할 수 있습니다.

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에서는 반드시 적용해보세요.