[Vue.js] Dynamic Route Matching(동적 라우트 매칭)
Web/Vue.js

[Vue.js] Dynamic Route Matching(동적 라우트 매칭)

728x90
반응형

해당 유저의 마이페이지에 url로 접근하는 경우 동일한 url 패턴을 보이게 된다. 예를 들어 /user/yeji 또는 /user/deokgi 처럼 비슷한 패턴의 url이 동일한 컴포넌트에 매칭되는 경우 동적 라우트 매칭을 사용한다. 동적 세그먼트는 콜론(:)부터 시작해서 작성하는데 예를 들었던 /user/yeji, /user/deokgi 에서 yeji, deokgi 처럼 바뀌는 부분이다.

 


 

 

나는 인스타 클론코딩을 할 때 유저 페이지에 동적 라우트 매칭을 사용했다. 

아래는 인스타 클론 코딩에서 사용한 동적 라우트 매칭👇

// router- index.js에 경로 설정
Vue.use(VueRouter)
  const routes = [
 {
    //dynamic route matching
    path:'/:username', // 동적 세그먼트는 콜론부터 시작
    name: 'Profile',
    component: ProfileView,
  }
]

 

 

동일한 라우트에는 여러 동적 세그먼트가 붙을 수 있고 세그먼트값을 불러올 때는 '$route.params.동적세그먼트' 로 접근한다. 여기선 $route.params.username 으로 세그먼트값을 username 변수에 담아 사용 (-> 그 다음 axios로 서버와 통신하여 해당 유저네임에 맞는 유저 정보를 불러왔음)

 

// 유저 정보를 보여주는 MyInfo.vue 컴포넌트
<template>
  <div>
    <h1>MyInfo</h1>
    <span>
      {{ info }}
    </span>
  </div>
</template>

<script>
import axios from 'axios'
const SERVER_URL = 'http://localhost:8000'

export default {
  name: 'MyInfo',
  data() {
    return {
      username : this.$route.params.username,
      info: []    
    }
  },
  methods: {
    fetchInfo() {
      axios.get(SERVER_URL + '/accounts/'+ this.username)
        .then(res => this.info = res.data)
        .catch(err => console.error(err))
    }
  },
  created() {
    this.fetchInfo()
  }
}
</script>

<style>

</style>

 

쉽게 말해 dynamic route matching은 동일한 패턴 구조를 보이는 url들을 하나의 컴포넌트에 연결하고 싶을 때 사용. 동적 세그먼트(url에서 바뀌는 부분) 값을 불러올 때는 this.$route.params 사용

 

 

공식문서 참조

: https://router.vuejs.org/guide/essentials/dynamic-matching.html#reacting-to-params-changes

 

Dynamic Route Matching | Vue Router

Dynamic Route Matching Very often we will need to map routes with the given pattern to the same component. For example we may have a User component which should be rendered for all users but with different user IDs. In vue-router we can use a dynamic segme

router.vuejs.org

 

반응형