首页 > 解决方案 > vue js和strapi - 控制台说属性未定义但不是 - 它呈现在页面上

问题描述

为什么会发生这样的事情?

我有一个 vue 应用程序,它指向一个 Strapi CMS 实例,并且正在使用 API 在页面上呈现。

我稍微改变了我的后端查询,响应有点不同,所以我必须去数组索引 0 到它({{ webinar[0].webinar_title }})但由于某种原因它说它是未定义的,即使它仍然呈现在页面上:

<template>
    <section class="webinar-information">
        <div>
          <h1>{{ webinar[0].webinar_title }}</h1>
          <p>{{ webinar[0].webinar_description }}</p>
        </div>
    </section>
</template>

<script>
import axios from 'axios';

export default {
  name: 'WebinarSingle',
  data () {
    return {
      webinar: [],
      error: null
    }
  },
  async mounted () {
    try {
      const response = await axios.get('http://localhost:1337/webinars?webinar_slug=' + `${this.$route.params.id}`)
      this.webinar = response.data
      console.log(this.webinar)
      // this is returning the title why is it "undefined" in the console?
      console.log('the title is: ' + this.webinar[0].webinar_title)
    } catch (error) {
      this.error = error;
    }
  },
  props: {
    header: String
  }
}
</script>

<style scoped>

</style>

输出是正确的,如下所示:

在此处输入图像描述

但我的控制台是这样的:

在此处输入图像描述

的输出

http://localhost:1337/webinars?webinar_slug=' + ${this.$route.params.id}``

是:

http://localhost:1337/webinars?webinar_slug=accelerating-the-close-with-technology-and-automation

当您控制台记录响应时,它看起来像这样:

在此处输入图像描述

所以我必须通过[0]“工作”来访问所有内容,但控制台说它是未定义的。为什么?

标签: javascriptnode.jsvue.jsstrapi

解决方案


当页面加载时,Vue 会尝试渲染你的模板:

<template>
    <section class="webinar-information">
        <div>
          <h1>{{ webinar[0].webinar_title }}</h1>
          <p>{{ webinar[0].webinar_description }}</p>
        </div>
    </section>
</template>

在这个时间点,webinar是你初始化它的,即[]. 当您尝试访问第一个元素时,这会导致您的错误。

然后 X 毫秒后,localhost:1337返回显示的响应。

要解决您的问题,您可以将 a 添加v-if="webinar && webinar.length"到模板中的根元素(不是模板元素),然后它只会webinar[0]在有元素时尝试访问。


推荐阅读