【问题标题】:vue js and strapi - console says property is undefined but it's not - it renders on the pagevue js和strapi - 控制台说属性未定义但不是 - 它呈现在页面上
【发布时间】:2021-07-12 20:47:35
【问题描述】:

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

我有一个 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] 来访问所有内容,但控制台说它是未定义的。为什么?

【问题讨论】:

  • 它最初不存在webinar: [],,所以&lt;section v-if="webinar.length" class="webinar-information"&gt;

标签: javascript node.js vue.js strapi


【解决方案1】:

当页面加载时,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 返回显示的响应。

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

【讨论】:

  • 知道了,这是一个最佳实践吗,等到它用条件完全渲染?
  • 视情况而定,有时我更愿意使用{{ (webinar &amp;&amp; webinar.length ? webinar[0].webinar_title : "-") }},这样一些页面仍然呈现,然后只是文本发生变化。
猜你喜欢
  • 2017-12-13
  • 2019-06-10
  • 1970-01-01
  • 2014-09-18
  • 2021-11-22
  • 2018-01-04
  • 2020-12-30
  • 2021-10-19
  • 2017-12-11
相关资源
最近更新 更多