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>
dispatch
로 action
에 userName
을 실어보내고
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
에서는 보낸 userName
을 name
으로 받아서 mutations
에 보낸다.(commit)
import해온 fetchUserInfo
에는 위에서 보여준 axios
로 url
을 보내는 함수가 들어있다.
mutations.js
export default {
SET_ITEM(state, item) {
state.item = item;
},
};
mutations
에서는 actions
에서 보내온 id
를 item
으로 받아서, 기존 state
에 있던 item
을 새로 받은 값으로 변경해준다.