javascript - 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]
“工作”来访问所有内容,但控制台说它是未定义的。为什么?
解决方案
当页面加载时,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]
在有元素时尝试访问。
推荐阅读
- c++ - 尽管一切看起来都很好,但值并没有交换
- sequelize.js - sequelize 中的批量删除和销毁有什么区别?
- adobe - Adobe Experience Manager - 用于无头消费的隐藏内容
- javascript - 仅接受十六进制输入
- java - 无法使用数据流访问记录类型数组列进行键值转换
- javascript - 正则表达式到特定字符串
- javascript - 如何仅在地图中执行所有等待之后才增加变量值,以便我可以执行承诺并行?
- python - Python 列表循环
- php - PHP / SQL:如果在表A和表B中更新后满足条件,则更新表C
- php - 如何从发送用户个人资料更改电子邮件中排除 WooCommerce 结帐?