Styling the native b-nav-item
The easiest solution would be to stick with b-nav-item
and apply your classes to the item using either the class
attribute, to add a class to the li
, or the link-classes
prop to add it to the rendered a
tag.
This way you let Bootstrap-Vue handle the collapse close, making it more future proof in case something changes in the future.
new Vue({
el: '#app'
})
<link href="https://unpkg.com/bootstrap@4.5.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap-vue@2.15.0/dist/bootstrap-vue.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.15.0/dist/bootstrap-vue.js"></script>
<div id="app">
<b-navbar toggleable="lg" type="light">
<b-navbar-brand to="#">
LOGO
</b-navbar-brand>
<b-navbar-toggle target="nav-collapse"></b-navbar-toggle>
<b-collapse id="nav-collapse" is-nav>
<b-navbar-nav>
<b-nav-item to="#">About Us</b-nav-item>
<b-nav-item to="#">Landlords</b-nav-item>
<b-nav-item to="#">Tenants</b-nav-item>
<b-nav-item to="#" link-classes="btn btn-primary text-white">
Valuation
</b-nav-item>
</b-navbar-nav>
</b-collapse>
</b-navbar>
</div>
Closing the collapse manually
Another option is to close the collapse by adding a click handler to your custom element in the navbar, that closes the collapse if open.
new Vue({
el: '#app',
data() {
return {
isCollapseOpen: false
}
},
methods: {
closeNavCollapse() {
if(this.isCollapseOpen) {
this.$root.$emit('bv::toggle::collapse', 'nav-collapse')
}
}
}
})
<link href="https://unpkg.com/bootstrap@4.5.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap-vue@2.15.0/dist/bootstrap-vue.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.15.0/dist/bootstrap-vue.js"></script>
<div id="app">
<b-navbar toggleable="lg" type="light">
<b-navbar-brand to="/">LOGO</b-navbar-brand>
<b-navbar-toggle target="nav-collapse"></b-navbar-toggle>
<b-collapse v-model="isCollapseOpen" id="nav-collapse" is-nav>
<b-navbar-nav>
<b-nav-item to="#">About Us</b-nav-item>
<b-nav-item to="#">Landlords</b-nav-item>
<b-nav-item to="#">Tenants</b-nav-item>
<b-button to="#" variant="primary" @click="closeNavCollapse">
Valuation
</b-button>
</b-navbar-nav>
</b-collapse>
</b-navbar>
</div>
Using a watcher to automatically detect route changes.
Alternatively you can use a watcher and detect when the route changes and manually close the collapse.