我正在尝试构建一个简单的测验应用程序。它有一些问题在数据库中。我正在使用 AXIOS 请求获取这些内容。 我正在做这样的事情:
var app = new Vue({
el:"#app",
data:{
currentQuestion:0,
question:{}
},
methods:{
next:function(){
this.currentQuestion+=1;
this.loadQuest();
} ,
loadQuest:function(){
axios.get('/questions').then((response)=>{
//console.log(response.data[this.currentQuestion]);
this.question = response.data[this.currentQuestion];
})
}
},
mounted(){
this.loadQuest();
},
});
在这里,您可以看到每当我单击下一个问题按钮时,就会调用 loadQuest() 并向服务器发送请求。有没有办法不在每次点击下一个按钮时发送请求,而只是增加 currentQuestion 变量并加载下一个问题?
最佳答案
- 将“问题”设为数组(而不是对象)
- 从一开始就了解所有问题
- 计算值“question”将自动监视“currentQuestion”的变化并相应更新值
const app = new Vue({ el: '#app', data: { currentQuestion: 0, questions: [], }, mounted() { axios.get('/questions').then((response) => { // console.log(response.data[this.currentQuestion]); this.questions = response.data }) }, methods: { next () { this.currentQuestion += 1 } }, computed: { question () { return this.questions.length ? this.questions[this.currentQuestion] : {} } } })
关于javascript - VueJs 在测验应用程序中获取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49028763/