Bootstrap V5 and Vue 3.x have been released for a while, but the widely used BootstrapVue library is still based on Bootstrap V4 and Vue 2.x. A new version of BootstrapVue is under development, and there is an alternative project BootstrapVue 3 in alpha version. However, since Bootstrap is mainly a CSS framework, and it has dropped jQuery dependency in V5, it is not that difficult to integrate into a Vue 3.x project on your own. In this article, we will go through the steps of creating such a project.
Create Vite project
The recommended way of using Vue 3.x is with Vite. Install yarn and create from the vue-ts template:
1 2 3 4
yarn create vite bootstrap-vue3 --template vue-ts cd bootstrap-vue3 yarn install yarn dev
Add Bootstrap dependencies
Bootstrap is published on npm, and it has an extra dependency Popper, so let’s install them both:
yarn add bootstrap @popperjs/core
You may also need the type definitions:
yarn add -D @types/bootstrap
Use Bootstrap CSS
Just add a line to your App.vue file and you are free to use Bootstrap CSS:
Bootstrap provides JS plugins to enable interactive components, such as Modal, Toast, etc. There are two ways of using these plugins: through data attributes, or create instances programatically. Let’s take Modal for an example.
Through data attributes
First, you need to import the Bootstrap JS. In the following example, we import the individual Modal plugin. You can also import the full Bootstrap JS using import 'bootstrap'.
When the Launch button is clicked, data-bs-toggle tells Bootstrap to show or hide a modal dialog with the element ID indicated by data-bs-target. When the Close button is clicked, data-bs-dismiss indicates hiding the dialog that contains this button. data attribute is simple, but not flexible. In practice, we tend to use JS instance instead.
Through JS instances
From the Bootstrap document, we see the following instruction:
const myModalAlternative = new bootstrap.Modal('#myModal', options)
It creates a Modal instance on a DOM element with the ID myModal, and then we can call the show or hide methods on it. In Vue, we need to replace the element ID with a Template Ref:
We use v-model to control the visibility of the modal dialog. By watching the value of modelValue property, we call corresponding methods on the Modal instance. Also we have replaced the data-bs-dismiss with a function that changes the value of modelValue, because that should be the single source of truth of the modal state.