VueJS close hamburger on route change

Sabin Khanal
1 min readMay 19, 2021

If you are using bootstrap to create your vueJS application you might have noticed that while implementing the Vue Router the navbar toggle is not working as expected. It won’t close automatically when you navigate from one route to another.

Here’s the quick workaround for this,

  1. Add ref to our toggle button.
<div class="container"><a class="navbar-brand" href="#">Lokpath Converter</a><buttonclass="navbar-toggler"type="button"data-toggle="collapse"data-target="#navbarResponsive"aria-controls="navbarResponsive"aria-expanded="false"aria-label="Toggle navigation"ref="navbar"><span class="navbar-toggler-icon"></span></button><div class="collapse navbar-collapse" id="navbarResponsive"><ul class="navbar-nav ml-auto"><li class="nav-item active"><a class="nav-link" href="/">Home<span class="sr-only">(current)</span></a></li>....

2. Add route watcher, maybe in your App.vue file or you can use this code in the router module.

<script>export default {watch: {$route() {this.$refs.navbar.click(); //click on route change},},name: "App",components: {},};</script>

There are few other alternatives:

  • Wrapping the expanded area with v-if and toggling the isNavOpen variable on route change
  • Adding hide class to the expanded
  • Using jQuery (if already used) to collapse like,
$('#navbar-collapse').collapse('hide');

It’s everything you need to do to make it work. Hope it’s useful for you.

--

--