I want to use Bootstrap 5 with Vue 3. As Bootstrap 5 uses vanilla JS (no JQuery), can I use Bootstrap 5 directly in a Vue 3 project (without using Bootstrap-Vue)? Can someone guide me how to use Bootstrap 5 with Vue 3?
ベストアンサー1
Bootstrap 5 no longer needs jQuery so it's easier to use with Vue, and no longer requires a library like bootstrap-vue.
Install bootstrap as you would any other JS module in the Vue project using npm install or by adding it to the package.json
...
npm install --save bootstrap
npm install --save @popperjs/core
次に、Bootstrap CSS および JS コンポーネントを Vue プロジェクトのエントリポイント (つまり、src/main.js
) に追加します...
import "bootstrap/dist/css/bootstrap.min.css"
import "bootstrap"
次に、Bootstrap コンポーネントを使用する最も簡単な方法は、data-bs-
属性を使用することです。たとえば、Bootstrap Collapse コンポーネントは次のようになります...
<button
class="btn btn-primary"
data-bs-target="#collapseTarget"
data-bs-toggle="collapse">
Bootstrap collapse
</button>
<div class="collapse py-2" id="collapseTarget">
This is the toggle-able content!
</div>
または、任意の Bootstrap コンポーネントをインポートし、それを Vue コンポーネントとして「ラップ」することができます。たとえば、Popover コンポーネントは次のようになります...
import { Popover } from bootstrap;
const popover = Vue.component('bsPopover', {
template: `
<slot/>
`,
props: {
content: {
required: false,
default: '',
},
title: {
default: 'My Popover',
},
trigger: {
default: 'click',
},
delay: {
default: 0,
},
html: {
default: false,
},
},
mounted() {
// pass bootstrap popover options from props
var options = this.$props
var ele = this.$slots.default[0].elm
new Popover(ele,options)
},
})
<bs-popover
title="Hello Popover"
content="This is my content for the popover!"
trigger="hover">
<button class="btn btn-danger">
Hover for popover
</button>
</bs-popover>