# Vue學習#13 Component 元件化
###### tags: `Vue 直播班 - 2022 春季班` `Vue`
## 什麼是元件化 ( Component )?
**在網頁中常常會出現相同的元素或介面,若可以將此介面獨立出來並重複使用,就可以大大減少開發的時間與重新製作功能,透過元件化的方式將這些重複或是制式的介面獨立出來,在不同的頁面只要做引入該元件就可以使用**
範例:
```Vue
const app=Vue.createApp({
data(){
return{
text:'12321'
}
},
methods: {
},
mounted() {
},
});
// 全域註冊 寫在根元件(app=Vue.createApp)或其他子元件上
app.component('card',{ // card 為元件名稱,想要將元件弄在 HTML 上面就要在 HTML 上加上 `<card></card>`
data(){
return{
text:'內建元件',
}
},
template : `<div>{{text}}</div>` , // template 決定`<card></card>`渲染的地方要長什麼樣子
});
app.mount('#app');
```
## 元件化的好處
1. 可以單一出現,也可以元件包元件
2. 可以獨立運作,也可以重複使用
3. 減少需要重新撰寫相同功能的時間,以及減少重複多餘的程式碼
4. 資料都是獨立的狀態
5. 邏輯拆分,不同的功能使用獨立的元件進行運作
## 元件註冊
### 全域註冊
```=Vue
app.component('card',{
data(){
return{
text:'內建元件',
}
},
template : `<div>{{text}}</div>` //Template Literial
});
```
```=CSS
<card></card>
```
1. 寫在根元件(app=Vue.createApp)後方或其他子元件上
2. 範例的 card 是元件的名稱,如果要使用元件,在 HTML 上就要加上`<card></card>` ,元件的名稱是自己定義的
3. 範例的 data 跟根元件 (app=Vue.createApp) 的 data 是各自完全獨立的
4. template 模板運用,是看你想要這個元件長什麼樣子,有三種方式此處的方式為 Template Literial
5. 子元件要放在 createApp之後跟mount之前
### 區域註冊
```=Vue
<script>
const card2={
data(){
return{
text:"區域註冊的噢"
}
},
template: `<div>區域註冊card2:{{text}}</div>`,
}
const app=Vue.createApp({
data(){
return{
text:'12321'
}
},
components:{
card2
},
methods: {
},
mounted() {
},
});
app.mount('#app');
</script>
```
1. 先直接先定義一個元件 card2
2. 在根元件 ( Vue.createApp ) 新增一個 components:{} 並將 card2 這個元件放進去,就完成了區域註冊囉
#### 注意
1. 如果在子元件做區域註冊,根元件會找不到,第二點為解決辦法 (子元件裡面註冊子元件)
2. 如果在子元件註冊,並且在子元件的區域去執行該元件,就會變成該子元件下的子元件
## 三種模板運用 -- 決定想要子元件長什麼樣子 template
### 1. Template Literial
將想要的樣子直接寫在子元件內,在使用資料的時候不用就照著 Vue 的方式 ({{}}) 將資料直接渲染上去
```=Vue
template : `<div>{{ text }}</div>`
```
### 2.x-template type=“text/x-template”
用一個`script type="text/x-template" id="自訂名稱"` 將想要渲染的樣子寫在裡面,並在子元件的 template : 寫上要渲染標籤的 id
1. type="text/x-template" 是固定寫法
2. id 是自訂名稱的
```=Vue
<script type="text/x-template" id="forCardTemplate">
<div>{{text}}</div>....模板樣式
</script>
```
```=Vue
template:''#forCardTemplate' //元件的template填上模板id
```
1. **注意事項!!! 子元件要放在 createApp之後跟mount之前**
## 重點!!
<font color='red'>### 不只元件註冊的資料是獨立的,渲染到畫面上的時候,input等運用資料的地方,資料也都是獨立的 </font>
<font color='red'>### template 也不會共用,但是元件是可以重複使用的</font>
## 參考
[Day15 萬丈高樓平地起(3):元件 Components 簡介](https://ithelp.ithome.com.tw/articles/10220650)
[Vue 筆記 - Component 元件化基礎概念](https://hsuchihting.github.io/vue-js/20200917/334940023/)