【问题标题】:How can I debug Vue app?如何调试 Vue 应用程序?
【发布时间】:2017-08-30 18:17:03
【问题描述】:

我有一个从 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>

【问题讨论】:

    标签: javascript asynchronous vue.js vuejs2 vue-component


    【解决方案1】:

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

    首先将数据对象定义为ES6 Object Method 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)
      }
    }
    

    我不知道你想在哪里触发这个方法(点击时,创建或挂载实例时),但我会使用 created 钩子

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

    【讨论】:

    猜你喜欢
    • 2017-03-22
    • 2019-04-07
    • 2021-02-05
    • 2013-06-22
    • 2023-03-02
    • 2011-10-21
    • 2019-01-06
    • 2013-08-15
    相关资源
    最近更新 更多