Good day, I would like to hide bootstrap-5/Offcanvas when I click on link inside. Here is Offcanvas:
//Button activate Offcanvas
<button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasDarkNavbar"
aria-controls="offcanvasDarkNavbar">
<span class="navbar-toggler-icon"></span>
</button>
//Offcanvas
<div class="offcanvas offcanvas-end text-bg-dark" tabindex="-1" id="offcanvasDarkNavbar"
aria-labelledby="offcanvasDarkNavbarLabel">
<div class="offcanvas-header">
<h5 class="offcanvas-title" id="offcanvasDarkNavbarLabel">Menu</h5>
</div>
<div class="offcanvas-body">
<ul class="nav nav-pills flex-column mb-sm-auto mb-0 align-items-center align-items-sm-start" id="menu">
<li class="nav-item">
<router-link to="/about" class="nav-link link-info align-middle px-0">
<i class="fs-4 bi-house"></i> <span class="ms-1 d-none d-sm-inline">Home</span>
</router-link>
</li>
</ul>
</div>
</div>
In official docs they say:
You can create an offcanvas instance with the constructor, for example: var myOffcanvas = document.getElementById('myOffcanvas') OR var bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas)
and then use method "hide". I tried to use in router-link @click="hideThisCanvas" and then
methods: {
hideThisCanvas(){
let myOffcanvas = document.getElementById('offcanvasDarkNavbar')
myOffcanvas.hide();
}
}
but it gives the error myOffcanvas.hide is not a function
. Please, help!
you have to create an offcanvas instance with the constructor, for example:
methods: {
hideThisCanvas(){
let myOffcanvas = document.getElementById('offcanvasDarkNavbar')
let bsOffcanvas = bootstrap.Offcanvas.getInstance(myOffcanvas);
bsOffcanvas.hide();
}
}
OR
methods: {
hideThisCanvas(){
let myOffcanvas = document.getElementById('offcanvasDarkNavbar')
let bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas);
bsOffcanvas.hide();
}
}
Because using traditional document selectors is not ideal for modern JS framework, you can create a ref for your offCanvas like this.
<div ref="offCanvas" class="offcanvas offcanvas-start" tabindex="-1" id="example_canvas">
Then access it in your vuejs function the way you should
example
let myOffcanvas = this.$refs.offCanvas;
your final method should be something like this
methods: {
hideThisCanvas(){
let myOffcanvas = this.$refs.offCanvas;
let bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas);
bsOffcanvas.hide();
}
}
I do not know so much about vuejs but I hope you get concept now and it helps you.