본문 바로가기

programming/Vue

[Vue.js] #11 네비게이션 바(NavBar) 만들기

[specific concept]

1. 조건에 따라 class 값 추가/제거

- isOpened라는 boolean 변수의 값에 따라 open 추가/없음 토글 됨

- @click 속성으로 toggleMenu 함수 실행됨

<div id="hamburger-icon" :class="{open: isOpened}" @click="toggleMenu">

 

[예제 코드]

1. /componets/NavBar.vue 만들기

<template>
<header>
  <div id="brand"><router-link to="/">HOME</router-link></div>
  <nav>
    <ul>
      <li><router-link to="/about">About</router-link></li>
      <li><router-link to="/user">Users</router-link></li>
    </ul>
  </nav>
  <div id="hamburger-icon" :class="{open: isOpened}" @click="toggleMenu">
    <div class="bar1"></div>
    <div class="bar2"></div>
    <div class="bar3"></div>
    <ul class="mobile-menu">
      <li><router-link to="/about">About</router-link></li>
      <li><router-link to="/user">Users</router-link></li>
    </ul>
  </div>
</header>
</template>

<script>
export default {
  data() {
    return {
      isOpened : false
    }
  },
  methods: {
    toggleMenu() {
      this.isOpened = !this.isOpened
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
}
body {
  background-color: darkgray;
}
header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  background-color: black;
  padding: 0 10px;
}
header a {
  text-decoration: none;
}
ul {
  display: flex;
  list-style: none;
  gap: 20px;
}
li a {
  color: white;
}
#hamburger-icon {
  display: none;
  cursor: pointer;
}
#hamburger-icon div {
  width: 35px;
  height: 3px;
  background-color: white;
  margin: 6px 0;
}
.open .bar1 {
  transform: rotate(-45deg) translate(-6px, 7px);
}
.open .bar2 {
  opacity: 0;
}
.open .bar3 {
  transform: rotate(45deg) translate(-6px, -7px);
}
#brand {
  font-size: 32px;
  font-weight: 700;
}
#brand a {
  color: coral;
}
.mobile-menu {
  display: none;
}
@media only screen and (max-width: 600px) {
  header nav {
    display: none;
  }

  #hamburger-icon {
    display: block;
  }
}
</style>

 

2. App.vue 템플릿 상단 NavBar 추가하기

<script setup>
import CardList from './components/CardList.vue'
import NavBar from './components/NavBar.vue'
</script>

<template>
  <!-- <CardList/> -->
  <!-- <div>
    <router-link to="/">HOME</router-link>
    <router-link to="/about">About</router-link>
    <router-link to="/user">Users</router-link>
  </div> -->
  <NavBar />
  <div>
    <router-view></router-view>
  </div>
</template>

<style>
* {
  padding : 0px;
  margin : 0px;
}
</style>

 

[실행결과]