Ryan H
Ryan H

Reputation: 2953

Bootstrap Vue 2.9.0 Navbar collapse doesn't close on page change

Describe the bug

I'm using Bootstrap Vue 2.9.0 in my Nuxt JS 2.12.2 project. I have a Navbar component that I've made and have included it into my default.vue layout. I will attach my Navbar component contents to this issue.

When changing between pages, I need the menu to close again, however, I've only found the only way of doing this is with: bv::toggle::collapse, unfortuantly it seems that although this works, when then going back to my homepage from another page, the menu reopens itself, or it'll reopen when clicking a random link on the page.

How can I close the menu on page change and not open it until I click the toggle?

<template>
  <b-navbar sticky toggleable="lg" type="dark" variant="dark" class="header-nav bg-transparent position-absolute w-100 p-3">
    <b-navbar-brand to="/" class="font-weight-lighter p-3">
      Site Name
    </b-navbar-brand>

    <b-navbar-toggle target="nav-collapse--menu" style="z-index: 90;"></b-navbar-toggle>

    <b-collapse id="nav-collapse--menu" is-nav>
      <b-navbar-nav class="ml-auto custom-dropdown-menus" id="nav-nav">
        <b-nav-item to="/page1" class="text-white font-weight-light p-3">page1</b-nav-item>
        <b-nav-item to="/page2" class="text-white font-weight-light p-3">page2</b-nav-item>
      </b-navbar-nav>
    </b-collapse>
  </b-navbar>
</template>

<script>
export default {
  watch: {
    '$route' () {
      this.$root.$emit('bv::toggle::collapse', 'nav-collapse--menu')
    }
  }
}
</script>

Versions

Upvotes: 0

Views: 1924

Answers (1)

Troy Morehouse
Troy Morehouse

Reputation: 5435

<b-collapse> also supports v-model at the same time. You can set up a route watcher, and set the v-model to false if the $route (or $route.path) changes

<template>
  <b-navbar sticky toggleable="lg" type="dark" variant="dark" class="header-nav bg-transparent position-absolute w-100 p-3">
    <b-navbar-brand to="/" class="font-weight-lighter p-3">
      Site Name
    </b-navbar-brand>

    <b-navbar-toggle target="nav-collapse--menu" style="z-index: 90;"></b-navbar-toggle>

    <b-collapse id="nav-collapse--menu" v-model="showCollapse" is-nav>
      <b-navbar-nav class="ml-auto custom-dropdown-menus" id="nav-nav">
        <b-nav-item to="/page1" class="text-white font-weight-light p-3">page1</b-nav-item>
        <b-nav-item to="/page2" class="text-white font-weight-light p-3">page2</b-nav-item>
      </b-navbar-nav>
    </b-collapse>
  </b-navbar>
</template>

<script>
export default {
  data() {
    return {
      showCollapse: false
    }
  },
  watch: {
    '$route' () {
      this.showCollapse = false
    }
  }
}
</script>

Upvotes: 2

Related Questions