跳至主要内容

[Vue CLI] 新增元件範例

TL;DR

Vue CLI 依據[Vue CLI]NPM安裝及專案初始化內的創建新專案步驟,創建新專案後,該專案的內容

參考資料

相關連結


建立BS5卡片元件

安裝Bootstrap

先暫停目前serve的執行狀態(ctrl+c),接著安裝bootstrap:

npm install bootstrap

有可能會遇到版本衝突等等的問題,這是因為目前已經不推薦使用vue cli了。 可以觀看npm所提供的建議

載入Bootstrap樣式

開啟src/App.vue,並且將檔案內的css修改如下:

<style lang="scss">
/* 使用@import載入剛剛所安裝的bootstrap */
@import 'bootstrap';
</style>

重新啟動npm run serve,可以看到目前的頁面排版已經變成bootstrap初始化的樣式了。

程式碼高亮

第一次開啟App.vue檔案時,可能程式syntax highligh沒有正常運作。

這時候在VSC上可以安裝Vue Language Features (Volar)這個套

就可以正確顯示syntax hightligh

建立卡片元件

src/component內新增一個Card.vue元件:

Card.vue
<template>
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{ title }}</h5>
<h6 class="card-subtitle mb-2 text-body-secondary">Card subtitle</h6>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="card-link">Card link</a>
<a href="#" class="card-link">Another link</a>
</div>
</div>
</template>

<script>
export default {
data () {
return {
title: 'this is card title'
}
}
}
</script>

元件命名規範

通常在建立元件時,我們會使用大寫開頭替元件命名

並且因為ESLint的規範關係,無法使用單一詞語去命名元件(如Card.vue就是不好的命名)

在About頁面使用卡片

About.vue
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
<CardExample></CardExample>
</template>

<script>
import CardExample from '@/components/CardExample.vue'
export default {
components: {
CardExample
}
}
</script>

使用import去將剛剛所建立的元件給引入。並且在Components中註冊該元件。

viewscomponents差異
  • views:完整的頁面,如首頁、關於頁面。裡面會再使用許多元件。
  • components:元件,沒有辦法自成一個完整的頁面。