Vue.js 未捕获类型错误:$props.currentQuestion未定义Vue
我遵循这个教程。 下面是我的QuestionBox.vue代码Vue.js 未捕获类型错误:$props.currentQuestion未定义Vue,vue.js,Vue.js,我遵循这个教程。 下面是我的QuestionBox.vue代码 <template> <div> {{ currentQuestion.question}} </div> </template> <script> export default { props: { currentQuestion: Object } } </
<template>
<div>
{{ currentQuestion.question}}
</div>
</template>
<script>
export default {
props: {
currentQuestion: Object
}
}
</script>
{{currentQuestion.question}
导出默认值{
道具:{
当前问题:对象
}
}
下面是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>
从“./components/Header.vue”导入标题
从“./components/QuestionBox.vue”导入QuestionBox
导出默认值{
名称:“应用程序”,
组成部分:{
标题,
问讯箱
},
数据(){
返回{
问题:[],
索引:0
}
},
挂载:函数(){
取('https://opentdb.com/api.php?amount=4&type=multiple',{
方法:“获取”
})
。然后((响应)=>{
返回response.json()
})
.然后((jsonData)=>{
this.questions=jsonData.results
})
}
}
#应用程序{
字体系列:Avenir、Helvetica、Arial、无衬线字体;
-webkit字体平滑:抗锯齿;
-moz osx字体平滑:灰度;
文本对齐:居中;
颜色:#2c3e50;
边缘顶部:60像素;
}
当我编译代码时,它成功了,但我没有得到预期的结果,即来自索引0的问题,相反,当我检查时,我得到的是错误未捕获类型错误:$props.currentQuestion未定义。
我被困在那里两天了,我做错了什么?请帮忙。提前谢谢。
在
问题框的
标签中添加v-if
。vue
:
{{currentQuestion.question}
这将阻止Vue在currentQuestion
中存在数据之前尝试渲染。然后当currentQuestion
变得真实时,它将被呈现
另请参见:在您的
上添加v-if=“问题[索引]”
。
您正在为挂载的钩子中的this.questions
获取数据,因此有一段时间questions
数组为空。因此,您将问题[index]
或问题[0]
作为道具传递给
。当时,问题[0]
的计算结果为未定义
。因此,在您的问题框中,您试图访问未定义的的属性question
<代码>{currentQuestion.question}
这会给您一个错误
<template>
<div>
<Header />
<QuestionBox
v-if="questions[index]"
:currentQuestion="questions[index]"
/>
</div>
</template>
您还可以将App.vue中的问题的初始值更改为问题:[{}]
尝试在您的@bassxzero上添加v-if=“questions[index]”
,谢谢,您说得对,我添加了您的代码,现在就可以了。但是你能解释一下为什么我需要那个v-if吗?教程中的导师没有添加该代码,工作正常。我对vue很陌生。非常感谢。那么我该如何结束这个问题并让你作为答案呢?哇,非常感谢你的解释。它现在工作正常。这将使组件在没有内容的情况下呈现给DOM。而且道具也没有定义。非常不必要。