[vue] vue-router 동적라우팅

Yeong·2023년 6월 5일

url 에 따라 기본틀은 유지하면서 안의 내용물만 바꿀 수 있도록 !

router > index.js

export const router = new VueRouter({
        mode : 'history',// loacalhost 뒤에 /#/을 삭제해주는 역할
        routes: [
        {
            path : '/news',
            component: NewsView,
        },
        {
            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/뒤에 오는 값만 변경되게 설정해주어서 해당 링크로 이동하게 한다.

유동 라우터와 vuex를 같이 사용하면!

UserView.vue

<script>
export default {
  name:"UserView",
  computed:{
    userInfo(){
      return this.$store.state.user;
    }
  },
  created() {
    // console.log(this.$route.params.id);
    const userName = this.$route.params.id;
   // axios.get(`https://api.hnpwa.com/v0/user/${userName}.json`);
    this.$store.dispatch('FETCH_USER',userName);
  }
}
</script>

dispatchactionuserName을 실어보내고

store > action.js

import {fetchUserInfo} from "@/api";

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을 보내는 함수가 들어있다

store > mutations.js

export default {
    SET_USER(state, user) {
        state.user = user;
    }
}

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

0개의 댓글