2017-09-22 140 views
1

我看到vue組件和內聯模板之間的奇怪行爲。Vue組件 - 渲染錯誤的位置

實施例#1:聯模板

這是工作正常。 vue組件不變,如下面的示例#2所示,唯一的區別是我將模板內容作爲內聯模板複製到標記中。

參見:https://jsfiddle.net/pobffmnv/

<div class="panel panel-primary"> 
    <div class="panel-heading">Current Clients</div> 
    <table class="table table-hover"> 
     <thead> 
      <tr> 
       <th>Client Name</th> 
       <th style="text-align: center;">No. Projects</th> 
       <th style="text-align: center;">Time (7 days)</th> 
       <th style="text-align: center;">Edit</th> 
      </tr> 
     </thead> 
     <tbody> 
      <clientlistitem inline-template> 
       <tr> 
        <td>Test</td> 
        <td style="text-align: center;">0</td> 
        <td style="text-align: center;">0</td> 
        <td style="text-align: center;"> 
         <div class="btn-group btn-group-xs" role="group"> 
          <button type="button" class="btn small btn-primary">Edit</button> 
         </div> 
        </td> 
       </tr> 
      </clientlistitem> 
     </tbody> 
    </table> 
</div> 

這正確顯示以下內容: Correct

例2:不是內聯

以下是我的Vue的模板。以下是對刪除內聯模板的代碼的更改。

參見:https://jsfiddle.net/Ld47hoy2/

<template> 
    <tr> 
     <td>Test</td> 
     <td style="text-align: center;">0</td> 
     <td style="text-align: center;">0</td> 
     <td style="text-align: center;"> 
      <div class="btn-group btn-group-xs" role="group"> 
       <button type="button" class="btn small btn-primary"> 
        Edit 
       </button> 
      </div> 
     </td> 
    </tr> 
</template> 
<script> 
    export default { 

    } 
</script> 

更新頁面代碼:

<div class="panel panel-primary"> 
    <div class="panel-heading">Current Clients</div> 
    <table class="table table-hover"> 
     <thead> 
      <tr> 
       <th>Client Name</th> 
       <th style="text-align: center;">No. Projects</th> 
       <th style="text-align: center;">Time (7 days)</th> 
       <th style="text-align: center;">Edit</th> 
      </tr> 
     </thead> 
     <tbody> 
      <clientlistitem></clientlistitem> 
     </tbody> 
    </table> 
</div> 

然而,在上述中,顯示以下內容: Incorrect

尋找在輸出的源代碼的頁面,它似乎把呈現的代碼之前,我的表...?我期待這是<tbody></tbody>標籤之間..

Strange output

有什麼理由會Vue公司輸出的代碼到該位置,而不是一個預期?

回答

3

這裏的問題是,使用in DOM templates模板首先由瀏覽器呈現,而HTML表格只允許某些種類的元素在裏面。既然如此,組件clientlistitem首先在表之外呈現,然後Vue編譯導致組件位於錯誤位置的模板。

要解決該問題,請使用is special attribute

<tbody> 
    <tr is="clientlistitem"></tr> 
</tbody> 

瀏覽器將接受這一事實,使得在正確的地方tr,但Vue公司將它解釋爲你的組件。

這是你的小提琴updated

+0

太棒了。所以你說,使用「是」總是比較安全,不管DOM中的任何位置? – Kannaiyan

+0

@Kannaiyan不,在特定的例子中,使用'is'是*只*是必需的。最安全的是使用字符串模板或單個文件組件。看看答案中的第一個鏈接。 – Bert

+0

令人驚歎!非常感謝,這很有魅力。 –