javascript - VueJs 在测验应用程序中获取问题

标签 javascript php vue.js vuejs2 vue-component

我正在尝试构建一个简单的测验应用程序。它有一些问题在数据库中。我正在使用 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 变量并加载下一个问题?

最佳答案

  1. 将“问题”设为数组(而不是对象)
  2. 从一开始就了解所有问题
  3. 计算值“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/

相关文章:

javascript - 预览内存中的内容 (javascript)

javascript - 为 "scrolling"页面设置(图像的)背景大小

javascript - 通过 AJAX 分配和使用 javascript 对象属性

php - 表单中可变数量的输入字段

css - 如何覆盖 Vue 组件中的作用域样式?

javascript - WordPress REST API 自定义表单提交 - React

javascript - codeigniter ajax 中的 gzip 压缩不起作用

PHP:通过插入逗号来格式化数字字符串

javascript - Firebase POST 自定义 ID

css - Vuetify v-select 组件宽度改变