vue.js - Vue emit will not be important in other component
问题描述
I am making a vue history quiz app, I have my questions retrived from an API. I want to show the questions, the correct answers and the user’s answers at the ResultScreen view. The way I have gone about it is to push the question into an array and $emit it. I can see it being stored in my vue tools, but for some reason it does not show in the component I want to show it in and consequently in on the resultScreeen.
The currentQuestion is an object that holds the question and the answers.
[the code that emits the array.]
storeQuestion: function (value) {
value = this.submitData.questionArray1
this.$emit('storeData', value)
console.log(value, 'my pants are on fire')
}
shows vue tools at it has been stored.
[the component where I want to project it and the function that will not show the question.]
<template>
<div>
<QuizQuestion
v-if="questions.length"
:currentQuestion="questions[index]"
@storeData="storeQuestion"
/>
<p v-if="questions">{{ questions }}</p>
<p v-else=""> loading.....</p>
</div>
</template>
<script>
// import { mapGetters } from 'vuex'
import QuizQuestion from '@/components/QuizQuestion.vue'
// se på gameplay hvor vi returner numcorrect, numtotal og numpoints, vi må se på hvordan vi kan importere verde
export default {
name: 'GameOver',
components: {
QuizQuestion
},
data () {
return {
questions: ''
}
},
methods: {
storeQuestion: function (value) {
this.questions = value
alert(value)
}
}
}
</script>
this.submitData.questionArray1.push(this.currentQuestion.question)
解决方案
问题在于您的模板,特别是这一行:
<p v-if="questions">{{ storeQuestion() }}</p>
因为该方法storeQuestion
没有return
字符串值,所以undefined
无论值questions
是什么,它都会返回。
在不知道存储数据的形状的情况下questions
,很难确切知道您想要什么代码,但我怀疑您想要类似的东西:
<p v-if="questions">{{ questions.text }}</p>
...也许...
<p v-if="questions">{{ questions[index].text }}</p>
……之类的。
但是,除了您关于如何显示某些内容的问题之外,您的数据结构让我感到困惑。我希望一个名为的数据变量questions
是一个数组,而不是对象(特别是因为您正在使用数组访问方法(例如.length
和questions[index]
它。我怀疑您将进行一些额外的更改,但这超出了范围关于在v-if
声明中显示信息的问题。