# 元件樣板建立及綁定方式(補) (4-2)
###### tags: `Vue`、`4. 元件`
2022.3.4
### 1. 樣板建立方式
#### template(一般)
```
<oldmoon></oldmoon>
<script>
const app = Vue.createApp({
data(){
return{
text:'這是內部資料'
}
},
})
app.component('oldmoon1',{
template:`<h2>這是元件1</h2>`
});
app.mount('#app');
</script>
```
#### x-template
```
<oldmoon></oldmoon>
<!-- 另外存放元件資料(template) -->
<script type="text/x-template" id='oldmoon_template'>
<h2>{{ text }}</h2>
</script>
<!------------------------------>
<script>
const app = Vue.createApp({
data(){
return{
text:'這是內部資料'
}
}
});
app.component('oldmoon',{
data(){
return{
text:'這是外部元件'
}
},
template:'#oldmoon_template'
});
app.mount('#app')
</script>
```
#### 單文件元件 (單一檔案包含HTML, JS, CSS)
  補 (較為簡單,使用方法與x-template接近)
### 2. 元件運用
#### 直接使用標籤名稱
```
<元件名稱></元件名稱>
```
#### 搭配v-for
```
//----------------Bootstrap套件-----------------
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
//----------------------------------------------\
<oldmoon v-for="i in array" :key="i"></oldmoon>
<script>
const app = Vue.createApp({
data(){
return{
array:[1,2,3]
}
}
});
app.component('oldmoon',{
template:`<div class="alert alert-primary" role="alert">這是外部資料</div>`
});
app.mount('#app')
</script>
```
#### 使用v-is綁定(可動態)
* 一般綁定
元件名稱一定要用「''」包裹
```
<div v-is="'元件名稱'"><div>
```
* 動態屬性
```
<input type="text" v-model="component_name">
<div v-is="component_name"></div>
<script>
const app = Vue.createApp({
data(){
return{
component_name : '請輸入元件名稱'
}}});
app.component('oldmoon1',{
template:`<h1>這是元件1</h1>`
});
app.component('oldmoon2',{
template:`<h1>這是元件2</h1>`
});
app.mount('#app')
</script>
```
備註:v2舊版寫法(不用記)
`<component v-bind:is="component_name"></component>`
### 3. 動態標籤實戰技巧
  表格製作,用非動態屬性調換元件,會讓HTML程式碼跑到最上面,所以要改用v-is方法讓元件渲染時不會跑格式。
```
<table class="table">
<thead>
<tr>
<th scope="col">標題1</th>
<th scope="col">標題2</th>
<th scope="col">標題3</th>
</tr>
</thead>
<tbody>
<tr v-is="'oldmoon'"></tr>
</tbody>
</table>
<script>
const app = Vue.createApp({
data(){
return{
text:'這是內部資料'
}
}
});
app.component('oldmoon',{
data(){
return{
text:['1-1','1-2','1-3']
}},
template:`<td v-for="(item,key) in text" :key="key">{{ item }} </td>`
})
app.mount("#app")
</script>
```