我正在学习本教程。 https://www.youtube.com/watch?v=4deVCNJq3qc
下面是我的 QuestionBox.vue 代码
<template>
<div>
{{ currentQuestion.question}}
</div>
</template>
<script>
export default {
props: {
currentQuestion: Object
}
}
</script>
下面是 App.vue 的代码
<template>
<div>
<Header />
<QuestionBox
:currentQuestion="questions[index]"
/>
</div>
</template>
<script>
import Header from './components/Header.vue'
import QuestionBox from './components/QuestionBox.vue'
export default {
name: 'app',
components: {
Header,
QuestionBox
},
data(){
return {
questions:[],
index:0
}
},
mounted: function(){
fetch('https://opentdb.com/api.php?amount=4&type=multiple',{
method: 'get'
})
.then((response) => {
return response.json()
})
.then((jsonData) => {
this.questions = jsonData.results
})
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
当我编译代码时,它成功了,但我没有得到预期的结果,这是来自索引 0 的问题,相反,当我进行检查时,我收到错误 Uncaught TypeError: $props.currentQuestion is undefined 。 我被困在那里 2 天,我做错了什么?请帮忙。提前致谢。
答案 0 :(得分:1)
在您的 v-if="questions[index]"
上添加 <QuestionBox>
。
您正在挂载的挂钩中获取 this.questions
的数据,因此有一段时间 questions
数组为空。因此,您将 questions[index]
或 questions[0]
作为道具传递给 <QuestionBox>
。那时,questions[0]
的计算结果为 undefined
。因此,在您的 QuestionBox 中,您尝试访问 question
的属性 undefined
。 {{ currentQuestion.question}}
这会给你一个错误。
<template>
<div>
<Header />
<QuestionBox
v-if="questions[index]"
:currentQuestion="questions[index]"
/>
</div>
</template>
答案 1 :(得分:0)
将 v-if
添加到 <div>
中的 Questionbox.vue
标签:
<template>
<div v-if="currentQuestion">
{{ currentQuestion.question }}
</div>
</template>
这将阻止 Vue 尝试渲染,直到 currentQuestion
中存在数据。然后当 currentQuestion
变为真值时,它将被渲染。
答案 2 :(得分:0)
您也可以在 App.vue 中将 questions
的初始值更改为 questions:[{}]