【问题标题】:Uncaught TypeError: $props.currentQuestion is undefined VueUncaught TypeError: $props.currentQuestion is undefined Vue
【发布时间】:2021-07-04 22:40:24
【问题描述】:

我正在关注本教程。 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天,我做错了什么?请帮忙。提前致谢。

【问题讨论】:

  • 尝试在您的&lt;QuestionBox 上添加v-if="questions[index]"
  • @bassxzero 谢谢你,你是对的,我添加了你的代码,现在好了。但是你能解释一下为什么我需要那个 v-if 吗?教程中的导师没有添加该代码并且工作正常。我对 vue 很陌生。谢谢。我该如何结束这个问题并让你成为答案?

标签: vue.js


【解决方案1】:

也可以在App.vue中将questions的初始值改为questions:[{}]

【讨论】:

  • 这会将组件渲染到没有内容的 DOM。道具将是未定义的。非常没必要。
【解决方案2】:

Questionbox.vue 中的&lt;div&gt; 标记中添加v-if

<template>
  <div v-if="currentQuestion">
    {{ currentQuestion.question }}
  </div>
</template>

这将阻止 Vue 尝试渲染,直到 currentQuestion 中存在数据。然后当currentQuestion 变为真时,它将被渲染。

另请参阅:https://stackoverflow.com/a/41052023/2073738

【讨论】:

    【解决方案3】:

    在您的&lt;QuestionBox&gt; 上添加v-if="questions[index]"。 您在挂载的钩子中获取this.questions 的数据,因此有一段时间questions 数组为空。所以你将questions[index]questions[0] 作为道具传递给&lt;QuestionBox&gt;。那时,questions[0] 的计算结果为 undefined。因此,在您的 QuestionBox 中,您尝试访问 undefined 的属性 question{{ currentQuestion.question}} 这会给你一个错误。

    <template>
      <div>
        <Header />
        <QuestionBox 
        
        v-if="questions[index]"
        :currentQuestion="questions[index]"
    
        />
      </div>
    </template>
    

    【讨论】:

    • 哇非常感谢您的解释。现在工作正常。
    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2015-01-14
    • 2014-07-06
    • 2014-09-01
    相关资源
    最近更新 更多