본문 바로가기
카테고리 없음

vue.js 네비게이션 만들기

by step 1 2021. 8. 10.
반응형

부트스트랩이용

공식 문서

https://getbootstrap.com/docs/5.1/components/navs-tabs/

 

Navs and tabs

Documentation and examples for how to use Bootstrap’s included navigation components.

getbootstrap.com

 

Router 공식 문서

https://next.router.vuejs.org/api/#to

 

API Reference | Vue Router

API Reference Props to Type: RouteLocationRawDetails:Denotes the target route of the link. When clicked, the value of the to prop will be passed to router.push() internally, so it can either be a string or a route location object. Home Home Home Home User

next.router.vuejs.org

대쉬 케이스와 파스칼 케이스 둘다 사용 가능하다.(예제는 대쉬케이스로 작성되었다.)

 

RouterLink 컴포넌트를 이용해서 라우터 기능을 사용한다.(a 태그 대신)

Header.vue 파일 생성

<template>
  <header>
    <div class="nav nav-pills">
      <div
        v-for="nav in navigations"
        :key="nav.name"
        class="nav-item">
        <RouterLink
          class="nav-link"
          active-class="active"
          :to="nav.href">
          {{ nav.name }}
        </RouterLink>
      </div>
    </div>
  </header>
</template>

<script>
export default {
  data() {
    return {
      navigations: [
          {
            name: 'Search',
            href: '/'
          },
          {
            name: 'Movie',
            href: '/movie'
          },
          {
            name: 'About',
            href: '/about'
          }
      ]   
    }
  }
}
</script>

배열데이터를 이용하여 각 name마다 url을 가지도록 정의한다.

v-for 기능을 이용하여 배열 데이터가 모두 출력되도록 설정해준다.

 

RouterLink 컴포넌트안에 to 속성을 이용하여 클릭할 때 해당 Url로 이동하도록 정의한다.

 

App.vue 파일 수정초기 화면에 header 부분이 보이도록 정의해준다.

<template>
  <Header />
  <RouterView />
</template>

<script>
// 네비게이션 가져오기
import Header from '~/components/Header.vue'
export default {
  components: {
    Header
  }
}
</script>
<style lang="scss">
// main.scss 플러그인을 가져온다.
@import "~/scss/main.scss";

</style>

 

index.js(페이지를 관리하는 js 파일) 수정

 새로운 페이지를 추가해준다.

// 라우터 패키지 가져오기
import { createRouter, createWebHashHistory} from 'vue-router'
// 라우터를 위해 컴포넌트 가져오기
import Home from './Home'
import About from './About'
import Movie from './Movie'

// 내보내기
export default createRouter({
  // Hash
  // https://google.com/#/search
  // hash 모드를 사용(중간의 /#/이 추가된다.), 페이지를 새로고침하였을때 404에러를 방지해준다.
  // history 모드도 있지만 간단한 처리를 위해서 hash를 사용하였다.(서버쪽에 설정을 추가해 줘야한다.)
  history: createWebHashHistory(),

  // pages: 페이지를 관리할때 사용되는 옵션
  // https://google.com/
  // url에 입력값에 따라 실행될 컴포넌트 지정
  routes: [
    {
      path: '/',
      component: Home
    },
    {
      path: '/about',
      component: About
    },
    {
      path: '/movie',
      component: Movie
    }
  ]
})

 

브라우저 확인

반응형