Today I Learned 53 - Vue / Dynamic Route Matching with Params

angie·2022년 11월 10일

Vue.js

목록 보기
11/12
post-thumbnail

1.Dynamic Route Matching with Params

  • URL의 parameter를 통해 동적 인자를 전달하는 방법
  • URL의 parameter로 전달한 값을 변수처럼 사용할 수 있다.
  • route 추가할 때 동적 인자를 명시

1) params

사용자의 ID에 따라 다른 변수를 사용하여 렌더링해야하는 컴포넌트가 있을 때, 해당 변수를 URL의 매개변수로 전달한다.

// User Component
const User = {
  template: '<div>User {{ $route.params.id }}</div>',
}

const routes = [
  // 매개변수는 콜론으로 표시됨
  { path: '/users/:id', component: User },
]
  • URL로 전달한 매개변수 id는 $route.params.id로 접근할 수 있다.
  • this.$route.params는 모든 컴포넌트에서 사용할 수 있다.

여러개의 파라미터 전달하기

여러 params를 전달할 수도 있다. 이러한 params는 $route.params에서 그에 맞는 필드에 맵핑된다.

URL패턴URL예시$route.params
/users/:username/users/eduardo{ username: 'eduardo' }
/users/:username/posts/:postId/users/eduardo/posts/123{ username: 'eduardo', postId: '123' }

2. 활용 예시

1) 선언적 방식 네비게이션

// App.vue
<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
      <router-link :to="{ name: 'hello', params: { userName: 'ssafy'} }">Hello</router-link>
    </nav>
    <router-view/>
  </div>
</template>
  • router-link 태그의 to속성을 v-bind directive를 사용하여 이동할 경로의 이름과 전달할 파라미터를 객체로 작성하여 전달한다.

2) 프로그래밍 방식 네비게이션

// AboutView.vue
<template>
  <div class="about">
    <h1>This is an about page</h1>
    <button @click="toHome">Home</button>
    <input
      type="text" v-model="userName"
      @keyup.enter="getNameAndGo"
    >
  </div>
</template>

<script>
  export default {
    name: 'AboutView',
    data() {
      return {
        userName: null,
      }
    },
    methods: {
      toHome() {
        this.$router.push({ name: 'home'})
      },
      getNameAndGo() {
        this.$router.push({ name: 'hello', params: { userName: this.userName} })
      }
    }
  }
</script>
  • this.$router.push에 이동할 경로와 전달할 파라미터를 객체에 담아 인자로 전달한다.

3) (참고) lazy-loading

// router/index.js

const routes = [
  {
  	path: '/',
    name: 'home',
    component: () => import('../views/HomeView.vue')
  }
]
  • index.js 상단에 import문을 쓰지 않고, 해당 라우트로 이동할 때 import될 수 있도록 한다.
  • 해당 라우터가 동작할 때 매핑된 컴포넌트를 불러온다.
  • 모든 파일을 한 번에 로드하지 않기 때문에 최초 로딩 시간이 줄어든다.
profile
better than more

0개의 댓글