将 surveyjs 结果发送到 API

Send surveyjs result to API

我正在尝试将 surveyjs 结果发送到我的 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"
        });
      });
}

要访问 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所以外面的可以用。