【问题标题】:Send surveyjs result to API将调查结果发送到 API
【发布时间】:2019-10-13 08:03:18
【问题描述】:

我正在尝试将调查结果发送到我的 API。

在mounted() 中,我使用vue-resource 发出GET 请求,从我的dB 处获取问题,然后设置surveyjs。为了发送结果,我尝试在surveyJS onComplete 函数中使用this.$http.post,但我得到了Cannot read property 'post' of undefined。另外,我尝试监视 result 变量,但没有成功。

mounted() {
    this.$http
      .get("myAPI")
      .then(res => res.json())
      .then(questions => {
        this.questions = questions;
        this.survey = new SurveyVue.Model(this.questions.pesquisa);
        this.survey.locale = "pt";

        this.survey.onComplete.add(function(survey) {
          this.result = survey.data;
          this.$http
          .post(
            `myAPI`,
            this.result,
            { headers: { "Content-Type": "application/json" } }
          )
          .then(response => {
            console.log(response);
            UIkit.notification({
              message: "Success",
              pos: "top-center",
              status: "success"
            });
          })
          .catch(error => {
            console.log(error);
            UIkit.notification({
              message: "Erro",
              pos: "top-center",
              status: "danger"
            });
          });
        }); 
      })
      .catch(error => {
        console.log(error);
        UIkit.notification({
          message: "Error",
          pos: "top-center",
          status: "danger"
        });
      });
}

【问题讨论】:

    标签: javascript vue.js vue-resource surveyjs


    【解决方案1】:

    要访问onComplete.add() 参数内的this,您可以将常规函数替换为箭头函数:

    this.survey.onComplete.add(survey => {
      this.result = survey.data;
      /* rest of your code... */
    })
    

    另一种方法是将this放入一个变量中,该变量可用于访问外部this

    const that = this;
    this.survey.onComplete.add(function(survey) {
      that.result = survey.data;
      /* rest of your code... */
    })
    

    阅读更多关于this的信息。

    它的要点是在函数内部,函数的this 覆盖组件的this,除非它是一个箭头函数,它故意没有this,所以外部的可用。

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 2017-03-11
      • 2021-10-24
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多