[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>
[실행결과]
'programming > Vue' 카테고리의 다른 글
[Vue] 하위 input 컴포넌트에 상위 data 연결 (emit & v-model) (0) | 2022.07.19 |
---|---|
[Vue] textarea 조건부 랜더링시 focus 이동 안되는 케이스 해결 -> $ref.focus() & nextTick() 메소드 (0) | 2022.07.19 |
[Vue.js] #10 vue-router 데이터 전달하기 (params, props) (0) | 2022.03.04 |
[Vue.js] #9 vue-router 사용하여 메뉴 navigation 링크만들기 (0) | 2022.03.04 |
[Vue.js] #8 css에서 vue 제공 변수 사용하기 (0) | 2022.03.04 |