2017-04-05 96 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