2017-04-05 97 views
1

我有一個從RESTful API獲取json的代碼。但它只顯示.container,它說項目數組中沒有任何東西。神祕的是它沒有顯示任何關於它的錯誤。所以我試圖調試它,顯示使用console.log獲取結果,所以我在代碼下添加了像let result = await fetch('video').then(res => res.json()),但它沒有在瀏覽器控制檯上顯示任何內容。好像它不運行的異步getData功能,但我不知道..如何調試Vue應用程序?

<template lang="pug"> 
.container 
    .columns(v-for="n in lines") 
    .column.is-3.vid(v-for='item in items') 
     .panel 
     p.is-marginless 
     a(:href='item.videoId') 
      img(:src='item.thumbnail') 
     .panel.vidInfo 
      .columns.hax-text-centered 
      .column 
       .panel-item.reddit-ups 
       span {{ item.score }} 
       i.fa.fa-reddit-alien.fa-2x 
       .panel-item.reddit-date 
       i.fa.fa-calendar.fa-2x 
</template> 
<script> 
export default { 
     name: 'main', 

     data:() => ({ 
     items: [], 
     lines: 0 
     }), 

     async getVideo() { 
     this.items = await fetch('/video').then(res => res.json())  
     this.lines = Math.ceil(this.items.length/4) 

     } 
    } 
    </script> 

回答

1

有在你的代碼的幾個問題,和控制檯應該提醒你注意他們。

首先定義數據對象ES6對象方法的簡寫,儘量避免箭頭功能:

data() { 
    return { 
    items: [], 
    lines: 0 
    } 
} 

那麼我想獲得視頻的方法,所以它應該在的方法放置的物體:

methods: { 
    async getVideo() { 
     this.items = await fetch('/video').then(res => res.json())  
     this.lines = Math.ceil(this.items.length/4) 
    } 
} 

我不知道你要(在創建或安裝時,例如在點擊)觸發這個方法,但我會用創建掛鉤

<script> 
export default { 
     name: 'main', 

     data() { 
     return { 
      items: [], 
      lines: 0 
     } 
     }, 

     methods: { 
     // I don't think you need async/await here 
     // fetch would first return something called blob, later you can resolve it and get your data 
     // but I suggest you to use something like axios or Vue reource 
     async getVideo() { 
      await fetch('/video') 
       .then(res => res.json()) 
       .then(items => this.items = items)  
      this.lines = Math.ceil(this.items.length/4) 
     } 
     }, 

     created() { 
     this.getVideo() 
     } 
    } 
    </script> 
+0

我非常讚賞它非常有幫助!如果可以的話,你會幫我解決這個問題嗎? http://stackoverflow.com/questions/43224096/how-can-i-add-a-element-everytime-after-4-elements-in-vue-js – yaomohi