How can I make a bootstrap offcanvas disappear in Vue 3 after clicking a router-link?

Hey there! I'm looking to close the bootstrap-5 Offcanvas when I click on a link inside it. Here's the code for the 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>

The official docs mention:

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 utilize the "hide" method. I attempted to use @click="hideThisCanvas" in the router-link and then

methods: {
  hideThisCanvas(){
    let myOffcanvas = document.getElementById('offcanvasDarkNavbar')
    myOffcanvas.hide();
  }
}

but it's throwing the error

myOffcanvas.hide is not a function
. Any assistance would be greatly appreciated!

Answer №1

To utilize an offcanvas instance, you need to instantiate it with the constructor. Here's an 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();
      }
    }

Instead of using traditional document selectors, it is recommended to create a reference for your offCanvas like this.

<div ref="offCanvas" class="offcanvas offcanvas-start" tabindex="-1" id="example_canvas">

Then, you can access it within your vuejs function as follows

example

let myOffcanvas = this.$refs.offCanvas;

Your final method should look something like this

methods: {
      hideThisCanvas(){
        let myOffcanvas = this.$refs.offCanvas;
        let bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas);
        bsOffcanvas.hide();
      }
    }

I don't have extensive knowledge of vuejs, but I hope this explanation clarifies the concept for you and proves helpful.

Answer №2

"Clicking" toggler works as well. Implement a function that your router-links triggers when clicked:

function closeOffcanvas() {
   document.getElementById('offcanvasToggler').click()
}

The toggler must be assigned an id:

<button id="offcanvasToggler" class="navbar-toggler" data-bs-toggle="offcanvas" data-bs-target="#offcanvas" aria-controls="offcanvas">

The router simply triggers the function to simulate a click:

<router-link :to="{ name: 'home'}" class="nav-link" @click.prevent="closeOffcanvas()">

There may be a more elegant Vue-like code utilizing ref as mentioned earlier. However, this method serves its purpose for me. You can also refer to the close button if you have it, using

data-bs-dismiss="offcanvas"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using asynchronous file uploading with jQuery and ASP.NET for a seamless user experience

I recently came across an article on Async file upload in ASP.NET which you can find here. Although the process was working fine up until the .ashx file call, I encountered an issue where "context.Request.Files.Count" showed 0. Any help or suggestions wo ...

What is the best way to delete rows from an HTML table?

I am trying to update the table, but every time the setInterval function is triggered, the append method adds the same rows again. I want the old rows to be removed before inserting the new ones. $(document).ready(function() { function updateT ...

Interactive tables created using Google Visualization

I have a Google visualization data table that works well, but I am facing an issue with the width of the table. When I click as shown in the image, I call the function drawTable(); and then I encounter this: As you can see, the table does not have a width ...

Sharing methods between two components on the same page in Angular can greatly improve code efficiency

On a single page, I have two components sharing some methods and properties. How can I utilize a service to achieve this? See the sample code snippet below... @Component({ selector: 'app', template: '<h1>AppComponent1</h1>' ...

What is the reason that selection disappears when right-clicking on highlighted text to bring up the context menu?

Currently, I am utilizing Material UI's context menu implementation in my project. On Chrome browser, everything is functioning flawlessly, as depicted below. Chrome: https://i.stack.imgur.com/i7eA1.gif However, I have encountered a peculiar issue ...

Notification for radio button selected

Looking to trigger an alert message when a radio button is not selected? Check out the code below: <form method=post name="spendform" id="spendform"> <input name="price" type="radio" class="invest-coin-check" id="pricemethod" > <button typ ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

What are some ways to make session variables available for sub applications?

I am currently working on setting up an API to interact with a MongoDB database, which I have integrated as a subapplication. In my server controller, I have created a session variable. However, I am facing an issue where the session variables are not be ...

Ways to retrieve Data obtained in response using superagent

I am currently working on hitting an API and extracting the data received in response. To achieve this, I am utilizing superagent to retrieve the data from the API. I have inspected my network tab, however, I am encountering an issue where I want to extra ...

Having difficulty with the useState hook in a material ui functional component that integrates with Firebase

Currently, I am endeavoring to create a sign-up form utilizing a Material UI functional component. Within this form, I am aiming to trigger a signup event by using the "onClick" attribute attached to the sign-up button. My approach involves passing the ema ...

Encountered an unexpected error in Vue: "Maximum call stack size exceeded callWithAsyncErrorHandling - Uncaught Range

<button onClick="test">Test</button> Issue encountered in Vue 3 that caused significant troubleshooting: Error message: Uncaught RangeError: Maximum call stack size exceeded callWithAsyncErrorHandling https://i.sstatic.net/sW2TU.pn ...

Retrieving and securely storing information using fetch() on authenticated REST services

Currently, I have successfully set up a React application that communicates with a REST backend which is built using Python and Flask. The specific functionality I have achieved involves downloading data from a database and saving it as a CSV file through ...

How come my variable doesn't show up in the view even though I filled it in the controller?

I'm having trouble with my AngularJS setup. The angular.min.js file is located in the js folder, following a code example from O'Reilly's book. However, for some reason it is not working on my computer. //controller.js function HelloCont ...

Click on the navigation bar buttons to toggle between different divs and display multiple information boxes simultaneously

Here is the current code snippet... $("#contact").click(function() { if ( $( "#contact_div" ).length ) { $("#contact_div").remove(); } else { var html='<div id="contact_div" class="contact-info"><p>Contact info</p&g ...

Increase the value of (N) in the copied MongoDB file name

Are there any algorithms available to handle incrementing numbers in duplicate filenames? For instance, let's consider a simple collection of documents stored in a file collection: [ { "_id": "612ead8668bfcc4221a788f6" ...

What happens if I don't associate a function or method in the React class component?

Take a look at this straightforward code snippet that updates a count using two buttons with different values. import "./App.css"; import React, { Component } from "react"; class App extends React.Component { // Initializing state ...

Bootstrap-tour is incompatible with a row within a table structure

Is there a way to highlight a table row effectively? I've been struggling with it and tried using the fix mentioned in this bootstrap-tour issue here Check out this demonstration on jsFiddle: jsFiddle JAVASCRIPT $("#dialog").dialog(); var t = new ...

Error: Attempting to access a property of an undefined value, please verify the key name is

Attempting to incorporate dynamic elements into the assignment, I have written the following code: var contentList = Object.keys(content)[0]; $scope.model.currentLoadedContent[contentList] = content[Object.keys(content)[0]] When trying to execute the seco ...

Upon loading, make sure to click on the link located within the third <li> tag

I am working with a list (<ul>): <ul class="options_inner"> <li><a data-dk-dropdown-value=".option1"></a></li> <li><a data-dk-dropdown-value=".option2"></a></li> <li><a data- ...

What is the best way to create a clickable background for a modal window?

I am looking to add a chatbox feature to my website and have been utilizing Bootstrap Modal for this purpose. My goal is to keep the modal open even when the user clicks outside of it, while still allowing them to interact with the background of the websi ...