Reputation: 241
I created this Vue app with side overlay nav and I am trying to recreate it again using a better approach, but since I am new to Vue I do not how. Is there a better way to do this without using javascript DOM to select the element by ID and set it width, using just Vue? I know that there is a better way to do this this with Vue.
var openNav = () => {
document.getElementById('myNav').style.width = '50%'
}
var closeNav = () => {
document.getElementById('myNav').style.width = '0%'
}
new Vue({
el: '#app',
methods: {
openOverlay () {
openNav()
},
closeOverlay () {
closeNav()
}
},
})
$(function () {
openNav()
closeNav()
})
.navbar-left {
@include inputStyle(2em)
}
.navbar-icon {
outline: none;
border: 0;
box-shadow: none;
}
.navbar-icon::before {
content: '\F0C9';
font-family: 'FontAwesome', serif;
font-size: 24px;
}
.overlay {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0, 0.9);
overflow-x: hidden;
transition: 0.5s;
}
.overlay-content {
position: relative;
top: 25%;
width: 100%;
text-align: center;
margin-top: 30px;
}
.overlay a {
padding: 8px;
text-decoration: none;
font-size: 36px;
color: #818181;
display: block;
transition: 0.3s;
}
.overlay a:hover, .overlay a:focus {
color: #f1f1f1;
}
.overlay .closebtn {
position: absolute;
top: 20px;
right: 45px;
font-size: 60px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="container-fluid" id="app">
<div class="d-flex align-items-center navbar-left">
<button type="button"
@click="openOverlay"
class="navbar-toggler navbar-icon"
data-toggle="collapse" />
</div>
<div id="myNav" class="overlay">
<a href="javascript:void(0)"
class="closebtn" @click="closeOverlay">×</a>
<div class="overlay-content">
</div>
</div>
</div>
Upvotes: 1
Views: 600
Reputation: 50787
Assign a data property:
data () {
return {
open: false
}
}
now just use 1 function:
methods: {
toggleOverlay() {
this.open = !this.open
}
}
now just use the open
property to determine when the width should be set. for simplicity, we'll do it inline:
<div id="myNav" class="overlay" :style="{ width: open ? '50%': '0' }">
Now change both your click handlers to reference toggleOverlay
:
@click="toggleOverlay"
Upvotes: 3