Vue.js Routing-2

강정우·2023년 4월 4일
0

vue.js

목록 보기
25/72
post-thumbnail

nested route

const router = CreateRouter({
  history : createWebHistory(),
  routes : [
    {path : '/', component : 컴포넌트},
    {path : '/teams', component : 컴포넌트, children : [
      {path : ':teamId', component : 컴포넌트, props:true}
    ]}
  ],
  likeActiveClass : 'active'
})
  • 그렇다면 아래 코드와는 무슨 차이가 있을까?
const router = CreateRouter({
  history : createWebHistory(),
  routes : [
    {path : '/', component : 컴포넌트},
    {path : 'teams/:teamId', component : 컴포넌트, props:true}
  ],
  likeActiveClass : 'active'
})
  • 만약 코드의 중복성을 줄인다는 점에서 nested route를 사용하고 싶다면 밑에 children에 해당하는 커스텀 컴포넌트단에서 <router-view> 가 적혀있어야한다.

  • Vue 라우터가 어디로 로드할지 모르기 때문에 router-view없이 사용하면 동작을 안 한다.

  • children 옵션에 설정한 라우트는 더 이상 루트 라우트가 아니며 routes에 직접 등록되어 있지 않는다.
    대신 다른 라우트의 자식 라우트로서 작동하는데 App.vue 파일에 사용한 router-view 컴포넌트는 앱 전체에 사용하는 최상단의 컴포넌트로 오직 루트 라우트만 다룬다. 즉, routes 배열에 직접적으로 등록한 라우트만을.

  • 그러므로 자식 라우트는 router-view에 렌더링 되지 않는다.
    대신 현재 자식 라우트를 자식 컴포넌트로 정의한 부모 컴포넌트에 두 번째 router-view를 추가해야 한다.

  • 또한 nested route는 active 기준이 부모컴포넌트도 모두 활성화되었다고 판단하기 때문에 tab에 강조하기 좋다.
    (이때 추가되는 것은 likeActiveClass이지 router-link-exact-active가 아니다.)

named routes

const router = CreateRouter({
	history : createWebHistory,
    routes : [
   		...
        {
        	name:'teams',
        	path:'/teams',
            component:TeamsList,
            children:[
              name:'team-members'
              ...
            ]
        }
    ]
})
  • nested 라우트에 이름을 부여하여 해당 이름을 로드할 수 있도록 만든 것이다. 그리고 이를 사용하는 커스텀 컴포넌트를 봐보자.
<script>
export default {
  props: ['id', 'name', 'memberCount'],
  computed: {
    teamMembersLink() {
      // return '/teams/' + this.id + '?sort=asc';
      return {
        name: 'team-members',
        params: { teamId: this.id },
        query: { sort: 'asc' },
      };
      // this.$router.push({ name: 'team-members', params: { teamId: this.id } });
    },
  },
};
</script>
  • params는 객체에 이동하고자하는 목적지를 나타내는 것이다.

  • 이렇게 작성하면 우선 가독성과 유지관리에 탁월하다. 또 만약 이렇게 관리한다면 상위 라우트의 이름이 바뀌어도 어차피 식별자 처럼 해당 라우트의 이름을 부여하여 관리하기 때문에 컴포넌트 경로를 바꿀 필요가 없다.

  • 또 query 매개변수(queryString 말하는 거)로 key:value로 값을 전달할 수 있고 이를 접근하여 추가 로직을 작성할 수 있다.
    물론 이는 queryString이기 때문에 접근하려면 this.$route.query 으로 찍어보면서 접근하면 된다.

named router + <router-view>

  • 이건 어제 쓰이냐 바로 페이지(라우터) 별로 같은 레벨에서 서로 다른 컴포넌트를 로드해야할 때 사용하면 된다.
<template>
  <the-navigation></the-navigation>
  <main>
    <router-view></router-view>
  </main>
  <footer>
    <router-view name="footer"></router-view>
  </footer>
</template>
  • 이렇게 된다면 해당 라우터 설정을 변경해줘야한다.
const router = CreateRouter({
	history : createWebHistory,
    routes : [
   		...
        {
        	name:'teams',
        	path:'/teams',
            components:{ default:TeamsList, footer:TeamsFooter},
            children:[
              name:'team-members'
              ...
            ]
        }
    ]
})
  • component's' 에 키값으로는 여러 router-view를 구분하고 값으로는 router-view에 들어갈 컴포넌트가 들어간다.

query string

<router-link to="/auth?redirect=register">Log-in</router-link>
async submitForm() {
  this.formIsValid = true
  if (this.email === '' || this.password.length < 6) {
    this.formIsValid = false
    return
  }
  this.isLoading = true
  const actionPayload= {
    email: this.email,
    password: this.password
  }
  try {
    if (this.mode === 'login') {
      await this.$store.dispatch('login', actionPayload)
    } else {
      await this.$store.dispatch('signup', actionPayload);
    }
    const redirectUrl = '/'+(this.$route.query.redirect||'coaches')
    this.$router.replace(redirectUrl);
  } catch (err) {
    this.error = err.message || 'Failed to authenticate, try later'
  }
  this.isLoading = false
},
  • const redirectUrl = '/'+this.$route.query.redirect 요 부분이고 this.$route.query.쿼리스트링"키" 로 url에 접근하여 로직을 작성할 수 있다. 이때 $router가 아닌 $route 인 것을 인지하자!
profile
智(지)! 德(덕)! 體(체)!

0개의 댓글