Vue.js-v-for不呈现api调用响应数据

问题描述

我正在尝试呈现数据列表,但是似乎每当页面加载时它都不想显示数据。我的api调用可以正常工作并获取我需要的所有内容并将其设置为我的数据对象。这里的代码blogPosts一旦设置为一个对象数组即可。

<template>
<div>
    <div class="bw-blog-card" v-for="post in blogPosts" :key="post.id">
        <div class="bw-blog-card__profile"></div>
        <div class="bw-top-blog__top-card">
            <div>
            creator: {{ post.username }}
            </div>
            <div>
                {{ post.created_at }}
            </div>
            <div class="bw-blog-card__card-title">
                {{ post.title }}
            </div>
            <div>
                {{ post.description }}
            </div>
        </div>
    </div>
</div>
</template>

<script>
module.exports = {
    data: () => {
        return {
            blogPosts: []
        }
    },methods: {
        getBlogPosts: async () => {
            try {
                let { data } = await axios.get(`/devblog`)
                this.blogPosts = data.data
                console.log(this.blogPosts)
            }
            catch (error) {
                console.error(error)
            }
        }
    },created() {
        this.getBlogPosts();
    }
}
</script>

现在,如果我只是将blogPosts硬编码为对象数组,则此方法完全可以正常工作。我可以了解为什么它无法通过api调用工作吗?

解决方法

尝试将getBlogPosts: async () => {更改为async getBlogPosts() {,它应该可以工作:

Vue.config.devtools = false;
Vue.config.productionTip = false;

let app = new Vue({

  el: '#app',data() {
    return {
      blogPosts: []
    }
  },methods: {
    async getBlogPosts() {
      try {
        let {
          data
        } = await axios.get(`https://jsonplaceholder.typicode.com/posts`)
        this.blogPosts = data
        console.log(this.blogPosts)
      } catch (error) {
        console.error(error)
      }
    }
  },created() {
    this.getBlogPosts();
  }

})
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
  <div class="bw-blog-card" v-for="post in blogPosts" :key="post.id">
    <div class="bw-blog-card__profile"></div>
    <div class="bw-top-blog__top-card">
      <div>
        creator: {{ post.userId }}
      </div>

      <div class="bw-blog-card__card-title">
        {{ post.title }}
      </div>
      <hr/>
    </div>
  </div>
</div>