问题描述
在将动态值从 v-for 循环处理到我的数据库时面临主要问题。 在我的 Vue 应用程序中,我在 v-for 循环中显示问题,用户可以通过表单回答每个问题。除了用户输入之外,我还想将他们回答的问题(当前问题对象)的值传递到我的数据库 (Google Firebase)。
V-for 循环 + 表单看起来像这样::
Files.createTempFile(String prefix,String suffix,FileAttribute<?>... attrs)
数据对象:
<b-row
v-for="question in questions"
:key="question.content"
>
<form @submit.prevent="postAnswer">
<textarea v-model="content"></textarea>
<input v-model="authorname" />
<b-form-select v-model="authorage" value="select" name="age">
<b-form-select-option v-for="n in 99" :value="n" :key="n">{{
n
}}</b-form-select-option>
</b-form-select>
<b-button type="submit">Submit your answer </b-button>
</form>
},
数据通过以下方式添加到 Firebase:
data() {
return {
authorname: null,authorage: null,content: null,question: null,questions:[],answers: [],};
现在如您所见,我不仅希望将用户的输入传递给我在数据库上的集合,而且还希望将他们在 v-for 循环中引用的问题传递给我。我怎样才能做到这一点?
非常感谢
解决方法
我将改变问题变量、v-for 和 v-models 以如下方式工作,并向 postAnswer 方法添加一个索引变量。
<b-row
v-for="(question,index) in questions"
:key="index">
<form @submit.prevent="postAnswer">
<textarea v-model="question.answer.content"></textarea>
<input v-model="question.answer.authorname" />
<b-form-select v-model="question.answer.authorage" value="select" name="age">
<b-form-select-option v-for="n in 99" :value="n" :key="n">{{
n
}}</b-form-select-option>
</b-form-select>
<b-button @click="postAnswer(index)" type="submit">Submit your answer </b-button>
</form>
</b-row>
数据看起来像:
data(){
return{
questions:[]
}
}
组装问题列表时,请确保添加答案键,例如:
this.questions = questions.map(q => {q.answer = {
'authorname': '','authorage': '','content': ''
}})
最后是 postAnswer 类似:
postAnswer(index){
db.collection('answers').add({
...this.questions[index].answer,// I didn't understand what question was,but you can just specify here
question: this.questions[index]
})
.then(docRef => this.$router.go( ))
.catch(error => console.log(err))
},
这种方式应该可以正常工作,如果我错过了什么,请告诉我