2017-06-21 80 views
1

我正在嘗試學習Vue並嘗試使用內聯模板和v-for循環來實現簡單測試。Vue inline-template with v-for - not defined

當我加載下面的頁面時,我收到以下錯誤,並且沒有內容呈現給屏幕。

[Vue警告]:屬性或方法「帖子」未在實例 上定義,但在渲染過程中引用。確保在數據選項中聲明反應性數據 屬性。

我是Vue的初學者,但任何幫助將不勝感激。

<!DOCTYPE html> 

<html> 
    <head> 
     <title>Vue Test</title> 

     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 

     <script src="http://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> 
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> 
     <script src="https://unpkg.com/[email protected]/dist/vue.js"></script> 
    </head> 

    <body> 
     <div id="vue-app" class="container"> 
      <post-list inline-template v-for="(post, index) in posts" :key="post.id"> 
       <div class="post"> 
        <h1>{{ post.subject }}</h1> 
       </div> 
      </post-list> 
     </div> 

     <script> 
      Vue.component('post-list', { 
       data: function() { 
        return { 
         posts: [ 
          { id: 0, subject: 'The first post subject' }, 
          { id: 1, subject: 'The second post subject' } 
         ] 
        } 
       } 
      }); 

      new Vue({ 
       el: '#vue-app' 
      }); 
     </script> 
    </body> 
</html> 

謝謝。

回答

1

你的v-for需要裏面的模板。 inline-template意思是裏面的所有東西都是這個模板。

組件將使用其內部內容作爲模板

v-for是不是裏面,所以它試圖遍歷post-list組件上的根Vue公司尋找posts,這是不那裏。

此外,迭代根元素將導致多個根(這是不允許的),所以我將v-for包裝在div中。

Vue.component('post-list', { 
 
    data: function() { 
 
    return { 
 
     posts: [{ 
 
      id: 0, 
 
      subject: 'The first post subject' 
 
     }, 
 
     { 
 
      id: 1, 
 
      subject: 'The second post subject' 
 
     } 
 
     ] 
 
    } 
 
    }, 
 

 
}); 
 

 
new Vue({ 
 
    el: '#vue-app' 
 
});
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script> 
 
<div id="vue-app" class="container"> 
 
    <post-list inline-template> 
 
    <div> 
 
     <div class="post" v-for="(post, index) in posts" :key="post.id"> 
 
     <h1>{{ post.subject }}</h1> 
 
     </div> 
 
    </div> 
 
    </post-list> 
 
</div>