# Template Component 資料沒有正確被塞入 tbody ###### tags: `學習 Vue` ## Vue 3.0 ## 我是怎麼寫的 ### Script (JS) ``` function GetEmployees() { var employeeApp = Vue.createApp({ data() { return { employees: [ { id: 1, name: "ABC", dept: "拍馬屁部隊" } ] }; } }) employeeApp.component('employee-item', { props: ['employee'], // property name ( 欄位名 ) template: "#my-component" }) employeeApp.mount("#myTable"); } ``` --- ### Script (vue template) ``` <script type="text/x-template" id="my-component"> <tr> <td>{{ employee.name }}</td> <td>{{ employee.dept }}</td> </tr> </script> ``` --- ### Html ``` <div class="row" id="myTable"> <table class="table table-bordered"> <thead> <tr> <th>姓名</th> <th>部門</th> </tr> </thead> <tbody> <employee-item v-for="item in employees" v-bind:employee="item" v-bind:key="item.id"> </employee-item> </tbody> </table> </div> ``` --- ## 發生甚麼事 有確實抓到資料,寫在畫面上,但是卻不如預期的跑版到 table 的外層(上方) ![](https://i.imgur.com/9tHTGxf.png) ## 為什麼會這樣 * 這是 table 的特性,在 tbody 後面都是接 tr 而我們卻接了我們新建的元件 * 自定義組件將作為無效內容懸掛,導致最終呈現的輸出中出現錯誤。 ## 解決他! 將 Html 的部分調整一下,寫成 tbody 可接受的 tr, 再**使用 v-is** 去告訴 vue 我的組件 employee-item 在這裡喔~! ※v-is value should be a JavaScript string literal ( v-is值應為JavaScript字符串文字 ) ### Html ``` <div class="row" id="myTable"> <table class="table table-bordered"> <thead> <tr> <th>姓名</th> <th>部門</th> </tr> </thead> <tbody> <tr v-is="'employee-item'" v-for="item in employees" v-bind:employee="item" v-bind:key="item.id"> </tr> <!-- 自定義組件將作為無效內容懸掛 --> @*<employee-item v-for="item in employees" v-bind:employee="item" v-bind:key="item.id"> </employee-item>*@ </tbody> </table> </div> ``` ## 參考 [參考-鐵人賽Day16 - Vue.js 基礎元件認識( 這邊用的是 vue 2.x )](https://ithelp.ithome.com.tw/articles/10219629) [參考-Vue官方3.0文件-DOM Template Parsing Caveats](https://v3.vuejs.org/guide/component-basics.html#dom-template-parsing-caveats)