본문 바로가기

기타/Vue

Vue Router 사용

요구 사항

검색 조건에 따라, 하단에 다른 테이블을 보여줘야하는 요구사항이 있었다.

아래와 같이, 검색 조건 부분까지 공통인데, 검색 시 Children Type이 First냐, Second냐에 따라 하단의 테이블이 달라져야 했다.

 

Vue Router 사용

Vue Router를 사용해서 요구사항을 구현하기로 했다.

Vue Router은 url Path에 따라 보여지는 자식 Component가 달라지는 것이다.

여기서는 Children Type이 First냐, Second냐에 따라 보여지는 테이블의 자식 Component가 달라지도록 한다.

Children Type URL 자식 Component
First /test/firstChild
ChildrenFirst
Second /test/secondChild ChildrenSecond

Vue Component 생성

Component를 아래와 같이 생성하였다. 

 

화면에서 보면 구성이 아래와 같다.

Children Type이 First이면 테이블 자리에 ChildrenFirst.vue가 오고, Second이면 ChidlrenSecond.vue가 온다.

 

TestMain.vue

TestMain.vue를 보면 소스 구성은 아래와 같다.

테이블을 나타낼 Component인 ChildrenFrist와 ChildrenSecond가 들어갈 곳에 router-view가 들어간다.

router-view는 url에 따라 자식 컴포넌트가 달라진다.

index.js

router에 있는 index.js에서 url path와 자식 컴포넌트를 매핑해준다.

 

아래와 같이 children에 path와 자식 컴포넌트를 매핑해주면 된다.

그러면, /test/firstChild일 때 router-view 부분에 ChildrenFirst 자식 컴포넌트가 들어간다.

 

TestSearch.vue

Search 버튼을 누를 때, 조건에 따라 테이블이 달라지도록 해야한다.

this.$router.replace를 이용해 검색할 때마다 path로 routing되도록 해줬다.

<template>
  <div id="test-search" class="k-content">
    <table class="k-table" width="100%">
      <tr>
        <td>
          Children Type
        </td>
        <td>
          <select v-model="childrenType">
            <option value="first">First</option>
            <option value="second">Second</option>
          </select>
        <td>
          Month
        </td>
        <td>
          <div style="display:inline-flex">
            <div>
              <kendo-datepicker v-model="month"
                                ref="month"
                                :start="'year'"
                                :depth="'year'"
                                :format="'yyyy-MM'">
              </kendo-datepicker>
            </div>
          </div>
        </td>
      </tr>
    </table>
    <div class="k-rtl" style="margin-top: 10px; margin-bottom: 10px">
      <kendo-button @click="searchBtn">Search</kendo-button>
    </div>
  </div>
</template>

<script>
import moment from 'moment'

const CHILDREN = {
  FIRST: 'first',
  SECOND: 'second'
}

export default {
  name: 'test-search',
  data () {
    return {
      childrenType: null,
      month: moment().format('YYYY-MM')
    }
  },
  methods: {
    searchBtn: function (e) {
      let path = '/test'
      const childrenTypeMap = {
        [CHILDREN.FIRST]: 'firstChild',
        [CHILDREN.SECOND]: 'secondChild'
      }
      path += '/' + childrenTypeMap[this.childrenType]

      this.$router.replace({ path })
    }
  }
}
</script>
<style>
</style>

결과

이렇게 Vue Router를 설정해주면 검색 조건에 따라 검색할 때마다 테이블이 변경된다.

 

참고로, /test 만 입력할 경우에는 매핑되는 path URL이 없으므로, 테이블 영역은 아무것도 나오지 않는다.

'기타 > Vue' 카테고리의 다른 글

mixins를 Vue의 Template에서 사용하는 방법  (0) 2023.03.19
Vue 강의 & 유용한 사이트 정리  (0) 2022.12.11