Vue를 공부해보자 (2)

빈코더·2021년 5월 13일
0
post-thumbnail

혹시나 1장을 안보고 오신분들은 1장을 보고 오는것을 추천드립니다.

1장 링크

1. Router연결

1장에서 http://localhost:8080/#/에 접속했을때 창에 아뭇것도 뜨지 않았다.

그 이유는 router설정을 했지만 news, jobs, ask에 도달하지 못했기 때문에 아뭇것도 보이지 않았다.

그러면 여기서 http://localhost:8080/#/에 접속했을때 http://localhost:8080/#/news로 접속이 되도록 설정을 해준다면?

접속과 동시에 http://localhost:8080/#/news로 접속이 될것이다.

이 방법은 redirect라는것을 사용해서 설정을 해줄것이다.

router폴더안에 있는 index.js파일을 다음과 같이 수정을 해주자.

export const router = new VueRouter({
  routes: [
    // path : url 주소
    // component : url 주소로 갔을 때 표시 될 컴포넌트
    {
      path: '/',          <--- 추가
      redirect: '/news',  <--- 추가
    },
    {
      path: '/news',
      component: NewsView,
    },
    {
      path: '/ask',
      component: AskView,
    },
    {
      path: '/jobs',
      component: JobsView,
    },
  ]
});

그리고 접속을 해보면 바로 news로 접속이 되는것을 확인이 가능하다

그럼 이제 두번째로 이제 news, jobs, ask의 버튼을 만들어서

버튼을 클릭하면 해당 링크로 접속이 되도록 코드를 작성해보자.

일단 Toolbar.vue라는 파일을 component 폴더안에 만들고

아래와 같이 입력을 해주자.
(tetur를 설치하신분은 vue 입력후 tab버튼)

<template>
  <div>
      header
  </div>
</template>

<script>
export default {

}
</script>

<style>

</style>

그리고 App.vue파일로 이동하여 Toolbar.vue파일을 등록을 해주자.

<template>
  <div id="app">
    <tool-bar></tool-bar>
    <router-view></router-view>
    // <ToolBar><ToolBar> 파스칼 케이스로 입력이 가능하지만 
    // vscode에서 tool-bar로 입력하고 tab을 누르면 자동완성을 지원한다.
    // 그리고 소문자로 입력하면 링크도 지원을 해줘서 해당 컴포넌트로 이동이 쉽다.
  </div>
</template>

<script>
import ToolBar from './components/Toolbar.vue'
export default {
  components: {
    ToolBar,
  }
}

그리고 다시 서버를 실행시키고 확인해보면!

위 사진과 같이 나오는것을 확인이 가능하다.

Vue개발자 도구로도 확인을 해보자.

F12를 누르면 확인이 가능하다.

Vue개발자도구는 필수이므로 없으면 꼭 설치를 해야한다.
다운로드 링크

설치를 했으면 Elements 옆에 >> 누르면 찾을수 있다.

ToolBar와 NewsView가 보이는것을 확인이 가능하다.

이제 ToolBar에 news, jobs, ask등록을 해보자.

ToolBar.vue파일로 이동해서 상단에 아래와 같이 추가해주자

<template>
  <div>
    <router-link to="/news">News</router-link> <-- 추가
    <router-link to="/ask">Ask</router-link>   <-- 추가
    <router-link to="/jobs">Jobs</router-link> <-- 추가
  </div>
</template>

router-link태그는 Vue 내부적으로 Vue router에서 화면에 A Tag로 변환해주고 부가적인 클래스를 제공해주는 역할을 한다.

그리고 to는 이동할 url을 적어주면 된다.

router 설정은 여기까지 하고

이제 스타일링을 해보자!

일단 App.vue하단에

  <style>
    body{
      padding: 0;
      margin: 0;
    }
  </style>

그리고 ToolBar.vue파일로 이동해서 아래와 같이 작성해주자.

// scoped를 적용하면 해당 컴포넌트만 적용이 된다.
<style scoped>
.header {
  color : white;
  background-color: #42b883; <-- 뷰의 색깔인 초록색
  display: flex;
  padding: 8px;
}
.header .router-link-exact-active {
  color: #35495e;
}
.header a{
  color: white;
}


여기까지 작성했으면 이제 실습으로 user랑 item에 관한 라우터를 직접 구현을 해보면 좋을거 같다.

그리고 추가적으로 index.js에 mode: 'history'를 추가해주자.

export const router = new VueRouter({
  mode: 'history', <-- 추가를 해주자 
  routes: [                         

mode: 'history'를 추가하면 http://localhost:8080/#/news 에서 #/를 제거할 수 있다.

여기까지하면 2장 끝

실습 정답
      ```
      import Vue from 'vue';
      import VueRouter from 'vue-router';
      import NewsView from '../views/NewsView.vue';
      import AskView from '../views/AskView.vue';
      import JobsView from '../views/JobsView.vue';
      import UserView from '../views/UserView.vue';  <-- 추가
      import ItemView from '../views/ItemView.vue';  <-- 추가

      Vue.use(VueRouter);

      // 
      export const router = new VueRouter({
        mode: 'history',
        routes: [
          // path : url 주소
          // component : url 주소로 갔을 때 표시 될 컴포넌트
          {
            path: '/',
            redirect: '/news',
          },
          {
            path: '/news',
            component: NewsView,
          },
          {
            path: '/ask',
            component: AskView,
          },
          {
            path: '/jobs',
            component: JobsView,
          },
          {					<-- 여기서 부터
            path: '/user',
            component: UserView,
          },
          {
            path: '/item',
            component: ItemView,
          }, 					<-- 여기까지 추가 
        ]
      });
      ```

      그리고 views폴더 안에 ItemView.vue파일과 UserView.vue파일을 
      생성하고 vetur를 사용해서 내용을 입력해주면 끝!
profile
미래의 리눅스 토발즈

0개의 댓글