如何调试 Vue 应用程序?

How can I debug Vue app?

我有一个代码可以从 RESTful API 获取 json。但它只显示 .container 并且它说 items 数组中没有任何内容。神秘的是它没有显示任何错误。所以我试图调试它显示使用 console.log 获取的结果,所以我在代码下添加了 let result = await fetch('video').then(res => res.json()),但它在浏览器控制台上没有显示任何内容。似乎它没有 运行 异步 getData 函数,但我不知道..

<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>

您的代码中几乎没有问题,控制台应该会就这些问题向您发出警告。

首先将数据对象定义为ES6对象方法Shorthand,尽量避免箭头函数:

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

那我猜get video是method,所以应该放在methods对象下面:

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>