[vue] vue-router 동적라우팅

김효식 (HS KIM)·2020년 8월 30일
0

react로 첫 프로젝트를 할 때 동적라우팅개념을 몰랐을 때, 어떻게 url에 따라 기본틀은 유지하면서 안의 내용물만 바꿀 수 있을지 굉장히 고민했었다. 그러다가 동적라우팅 개념을 알고나서 나름 혁신적인 경험을 했던 기억이 있다. vue에도 당연히 리액트와 같은 기능을 해주는 동적라우팅 개념이 있고, 사용법도 거의 유사하다.

routes.js

export const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/jobs',
      component: JobsView,
    },
    {
      path: '/user/:id',
      component: UserView,
    },
  ],
});

뒤의 url의 정보에 따라 바뀔 필요가 없는 페이지는 path를 위의 /jobs와 같이 해주면 되지만, url에 따라 페이지가 바뀌어야 하는 경우에는 뒤에 :를 찍고 변수명을 적어주면 된다. id가 아니어도 상관없지만, id를 적어주는 것이 컨벤션이다.

<p v-for="item in fetchedNews" :key="item">
  <router-link :to="`user/${item.user}`">{{ item.user }}</router-link>
</p>

router-link경로(:to)user/뒤에 오는 값만 변경되게 설정해주어서 해당 링크로 이동하게 한다.

User.vue

<script>
import axios from 'axios';

export default {
  created() {
    const userName = this.$route.params.id;
    axios.get(`https:/api.hnpwa.com/v0/user/${userName}.json`);
  },
};
</script>

created()내부에서 console.log(this.$route.params)을 찍어보면 객체안에 {id: user} 이런 식의 내용이 담겨있는 것을 확인할 수 있다. 그러므로 params에는 현재 url의 정보가 담겨 있는 것을 알수 있는데, 그 정보는 계속 유동적이므로 변수에 담아서 axios를 통해 정보를 받아오게 해준다.

유동 라우터vuex를 같이 사용하면...
User.vue

<script>
export default {
  created() {
    const userName = this.$route.params.id;
    this.$store.dispatch('FETCH_USER', userName);
  },
};
</script>

dispatchactionuserName을 실어보내고
action.js

import {
  fetchUserInfo,
} from '../api/index';

export default {
  FETCH_USER({ commit }, name) {
    fetchUserInfo(name)
      .then(({ data }) => {
        commit('SET_USER', data);
      })
      .catch((error) => console.log(error));
  },
};

FETCH_USER에서는 보낸 userNamename으로 받아서 mutations에 보낸다.(commit)
import해온 fetchUserInfo에는 위에서 보여준 axiosurl을 보내는 함수가 들어있다.

mutations.js

export default {
  SET_ITEM(state, item) {
    state.item = item;
  },
};

mutations에서는 actions에서 보내온 iditem으로 받아서, 기존 state에 있던 item을 새로 받은 값으로 변경해준다.

profile
자기개발 :)

0개의 댓글