開發 Vue 問題挑戰 ─ Vue 與 Bootstrap 結合

想說要挑戰 Vue 3 ,但後來才發現 Vuetify 不支持 Vue 3,所以才又決定要來挑戰 Vue 3 與 Bootstrap v5 版本做結合,結果一開始就出錯 😱 😱 😱。

簡單的先用 Vue CLI 開始 Vue 專案。

在用 NPM 載入 Bootstrap。

1
$ npm install bootstrap

之後再 src/main.js 中加入 import bootstrap from 'bootstrap'

問題一:如何讓畫面呈現 Bootstrap 樣式

做完上面步驟之後,開始在 *.vue 檔中使用 Bootstrap 會發現試行不通的。

後來在 stack overFlow 這篇 QA 找到解決方法 ─ 就是在 src/main.js 中加入 import 'bootstrap/dist/css/bootstrap.min.css';

問題二:如何自定義 Bootstrap 變量值

在製作網頁時,一定都會有幾個常見顏色,要怎麼把這些顏色放入 Bootstrap 中,讓我們在寫 Bootstrap 時,可以很直覺的用 primarysecondarydanger 等等來直接使用自定義的顏色,而不是 Bootstrap 預設的顏色。

這個問題研究了快 2 小時,因為一直在嘗試 Bootstrap Customize Sass 中的方法。

1
2
3
4
5
6
7
your-project/
├── scss
│ └── custom.scss
└── node_modules/
└── bootstrap
├── js
└── scss

新建了一個 custom.scss 。

但自定義樣式一直不成功,所以我還一直幫自定義樣式換位置(從 2 到 5),還是失敗,然後又嘗試把 custom.scss 移到 src/scss 下,一樣失敗了(這時候超想放棄改用 Vue2 加 Vuetify 的,改預設值超簡單) :sob: :sob: :sob:。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Custom.scss
// Option B: Include parts of Bootstrap

// 1. Include functions first (so you can manipulate colors, SVGs, calc, etc)
@import "../node_modules/bootstrap/scss/functions";

// 2. Include any default variable overrides here

$primary: #0074d9;
$danger: #ff4136;

$theme-colors: (
"primary": $primary,
"danger": $danger
);

// 3. Include remainder of required Bootstrap stylesheets
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/mixins";
@import "../node_modules/bootstrap/scss/root";

// 4. Include any optional Bootstrap CSS as needed
@import "../node_modules/bootstrap/scss/utilities";
@import "../node_modules/bootstrap/scss/reboot";
@import "../node_modules/bootstrap/scss/type";
@import "../node_modules/bootstrap/scss/images";
@import "../node_modules/bootstrap/scss/containers";
@import "../node_modules/bootstrap/scss/grid";
@import "../node_modules/bootstrap/scss/helpers";

// 5. Optionally include utilities API last to generate classes based on the Sass map in `_utililies.scss`
@import "../node_modules/bootstrap/scss/utilities/api";

// 6. Add additional custom code here

最後才在 Bootstrap Webpack and bundlers 中找到解答(原來也很簡單:stuck_out_tongue_closed_eyes:)!

只要在 src/scss 下創建 _custom.scssmain.scss 後,在 main.scss 中寫下:

1
2
@import "custom";
@import "~bootstrap/scss/bootstrap";

_custom.scss 下就直接寫下要自定義的樣式變量就好。

這時會發現還是沒有作用,還記的剛剛問題一中的解答嗎? Bootstrap 樣式得另外載入 main.js 喔,而原本的 import 'bootstrap/dist/css/bootstrap.min.css'; 可以不用寫了! :clap: :clap: :clap: