Exploring the Functionality of Bootstrap 5 Collapse Component with VueJS 2

I am attempting to implement the Bootstrap 5 "collapse" component on a button in my VueJS2 project, but I am uncertain about how to integrate it.

Within my single file component, the structure is as follows:

<template> section:

          <button
            class="btn btn-danger"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#collapseExample"
            aria-expanded="false"
            aria-controls="collapseExample"
          >
            Mark As Rejected
          </button>
          <div class="collapse" id="collapseExample">
            <div class="card card-body">
              Some placeholder content for the collapse component. This panel is
              hidden by default but revealed when the user activates the
              relevant trigger.
            </div>
          </div>

<script> section:

<script>
import Collapse from 'bootstrap/js/dist/collapse'
export default {
    ...
    methods: {
        // How can I manually enable the collapse feature using JavaScript???
    }
}
    ...
</script>

The Bootstrap documentation provided an example using vanilla JavaScript...but I need guidance on implementing it with VueJS.

Example of Bootstrap 5 Collapse in pure JavaScript:

var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'))
var collapseList = collapseElementList.map(function (collapseEl) {
  return new bootstrap.Collapse(collapseEl)
})

Answer №1

I found that I was overcomplicating this situation.

To implement Collapse in VueJS single file components using HTML data-attributes, all I needed to do was import the Collapse file like this:

import 'bootstrap/js/dist/collapse'

This approach also streamlined tree-shaking for me, as I could selectively import scripts when required.

Answer №2

There are various methods to achieve this goal. One approach is to integrate Bootstrap JS within a Vue method. Here's an example...

    mounted() {
        this.openCollapse()
    },
    methods: {
        openCollapse() {
            var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'))
            var collapseList = collapseElementList.map(function (collapseEl) {
              var bsCollapse = new bootstrap.Collapse(collapseEl)
              bsCollapse.show()
            })
        }
    }

See Demo


Alternatively, you have the option to transform the Bootstrap Collapse component into a reusable Vue component...

const collapse = Vue.component('bsCollapse', {
    template: `
        <div>
            <slot name="trigger"></slot>
            <slot name="target"></slot>
        </div>
    `,
    props: {
        toggle: {
            required: false,
            default: false
        },
        id: {
            required: true
        }
    },
    mounted() {
        var trigger = this.$slots['trigger'][0].elm
        var target = this.$slots['target'][0].elm
        target.classList.add('collapse')
        target.setAttribute('id', this.id);
        trigger.setAttribute('data-bs-target', '#' + this.id);
        trigger.setAttribute('data-bs-toggle','collapse');
        new Collapse(target, {toggle: this.toggle })
    },
})

And it can be used as follows...

    <bs-collapse id="collapse1">
            <button class="btn btn-info" slot="trigger">
                Bootstrap collapse
            </button>
            <div slot="target">Toggle the display of this collapsible content!</div>
    </bs-collapse>

Also refer to: Applying Bootstrap 5 with Vue 3

Answer №3

When I encountered this issue, I followed these steps to resolve it

  1. Firstly, make sure to install "@popperjs/core" and "bootstrap"
{
    "devDependencies": {

        ....
        
        "@popperjs/core": "^2.10",
        "bootstrap": "^5.1.3"
    }
}
  1. Next, you need to import the Collapse Class
import { Collapse } from 'bootstrap'
  1. Add a "ref" attribute to an element with the class "navbar-collapse"
ref="menuCollapse"
  1. Finally, call the class with the required parameter
new Collapse(this.$refs.menuCollapse, { toggle: false })

Here is an example of the complete component code:

<template>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <div class="container-fluid">
            <button
                class="navbar-toggler"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#navbarTogglerDemo01"
                aria-controls="navbarTogglerDemo01"
                aria-expanded="false"
                aria-label="Toggle navigation"
            >
                <span class="navbar-toggler-icon"></span>
            </button>
            <a class="navbar-brand" href="#">Foo brand</a>
            <div ref="menuCollapse" class="collapse navbar-collapse" id="navbarTogglerDemo01" >
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                        <a class="nav-link active" aria-current="page" href="#">Bar</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" aria-current="page" href="#">Bas</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</template>

<script>
import { Collapse } from 'bootstrap'

export default {
    mounted() {
        // eslint-disable-next-line no-new
        new Collapse(this.$refs.menuCollapse, { toggle: false })
    },
}
</script>

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

Looking for assistance with navigating through this URL using Python (requests, beautifulsoup, or selenium) or Javascript (node js, puppeteer)?

While attempting to gather data, I encountered an interesting pagination challenge on the following URL: My expertise in Web Scraping was put to the test as this website implemented a unique JavaScript-driven pagination. For the initial 5 pages, it simply ...

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...

Ensure that at least one checkbox is selected by using custom validation in jQuery

My form has checkboxes for gender (male and female) and a set of checkboxes for days of the week (Monday to Sunday). I need to set validation rules so that at least one gender and one day is selected. Below is my jQuery code: $(document).ready(function( ...

Utilizing JavaScript to eliminate objects from a collection and showcase a refreshed arrangement

On a simple webpage using bootstrap and js/jquery, data is fetched via ajax to create entries displayed to the viewer. The process involves: - making a request - parsing XML to create an array of objects with all the data - sorting by one property - cr ...

Ways to effectively pair a radio button with a dropdown menu

function radioCheck() { document.getElementById("last").checked = "checked"; } <label> <input type="radio" name="Ppub" value="" checked="checked">All Dates </label> <br> <label> <input type="radio" id="last" name="Ppu ...

Tips for preventing directly mutating a prop within a recursive component

The child operates on its own copy of the prop data and can notify the parent using `$emit` when a change occurs. Imagine dealing with a recursive tree structure, like a file system for example: [ { type: 'dir', name: 'music', childr ...

Issues with the functionality of minimized AngularJS JavaScript files

I combined all JS files into one and minified them, but now none of the site features are working. There were too many separate JS files to include individually, so I decided to merge them together. Is there a better method to reduce the number of HTTP r ...

What methods are available for retrieving specific XML entries using JavaScript?

Hey there, I'm dealing with this XML code <book> <bookname>book1</bookname> <author>authorman</author> </book> <book> <bookname>book2</bookname> <author>authorperson</author> </book ...

What is the best way to display a PDF in a web browser using a JavaScript byte array?

I have a controller that sends the response Entity as a byte array in PDF form to an ajax call. However, I am struggling to display it in the browser despite trying various suggestions from old Stack Overflow questions. Here is the response from the Sprin ...

access various paths to distinct iframes

<?php // Specify the directory path, can be either absolute or relative $dirPath = "C:/xampp/htdocs/statistics/pdf/"; // Open the specified directory and check if it's opened successfully if ($handle = opendir($dirPath)) { // Keep readin ...

Replace Euro symbols in JavaScript Regexp with grouping

Need assistance creating a Regex pattern for &#8203; € 14,50. After the replacement is completed, only 14,50 Can anyone provide guidance? ...

Is it possible to integrate applications developed using (JS, Node.js, Express, and MongoDB) into a Wordpress site?

After successfully building projects using JavaScript, Node.js, Express and MongoDB, I am now looking to incorporate them into my existing WordPress website. Is it possible to integrate these projects into WordPress, or would it be better to create a sep ...

An error occurred due to a class being instantiated within a module, resulting in an overflow of the

On line 7, the console.log statement prints out correctly. host.js "use strict"; var engine = require('./engine.js'); var base = require('./base.js'); var player = new base.Avatar(); console.log(player.x); class PillarGame extends ...

Secure your desktop application with OAuth by enabling HTTPS on localhost

I am currently in the process of developing a desktop application that integrates with Spotify's oauth api using the implicit grant flow as outlined here: My plan is to incorporate an "Authenticate" button, which when clicked will open the user' ...

Troubleshooting problem with Material-UI and Next.JS in Webpack

I have encountered an error while trying to add the code from this file: https://github.com/mui-org/material-ui/blob/master/examples/nextjs-with-styled-components-typescript/next.config.js When I include the next.config.js code provided below, I receive ...

Transforming CSV files into JSON format using d3.js

I'm encountering an issue when attempting to convert CSV to JSON. The following is the snippet of code I am using for the conversion: d3.csv("http://localhost:8080/Sample/flight.csv", function(flights) { //alert(flights); ...

Contrasting characteristics of class members in JavaScript versus TypeScript

Typescript, a superset of Javascript, requires that Javascript code must function in Typescript. However, when attempting to create class members in a typescript file using the same approach as Javascript, an error is encountered. CODE :- script.ts (types ...

Invoke JavaScript when the close button 'X' on the JQuery popup is clicked

I am implementing a Jquery pop up in my code: <script type="text/javascript"> function showAccessDialog() { var modal_dialog = $("#modal_dialog"); modal_dialog.dialog ( { title: "Access Lev ...

What is the proper way to implement v-model for a custom component within the Vue render function?

Below is the code that I am working with: ... var label_key_map = { a: "1", b: "2", c: "3", d: "4" } render: (h) => { var form_data = {} for (let key in label_key_map) { var form_item = h( 'FormItem', {props: {prop: key}}, ...

The navigation bar toggle feature seems to be malfunctioning in Bootstrap 5

I've encountered a problem with the navbar while using Bootstrap 5.0.2 dist. The toggler on the navbar expands and collapses, but it doesn't roll back after clicking the bar icon. I have implemented the fixed-top navbar from the Bootstrap 5 examp ...