javascript - 将 surveyjs 结果发送到 API

标签 javascript vue.js vue-resource surveyjs

我正在尝试将 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 因此外部可用。

关于javascript - 将 surveyjs 结果发送到 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56331253/

相关文章:

javascript - Vue.js 从另一个组件调用方法

javascript - ES6 标记模板实用性

javascript - jQuery:在所有事件发生变化后只运行一次回调函数

javascript - 在 pinia 商店中的状态更改后,vue 组件不会更新

vue.js - vue echarts 的自动调整大小不起作用

javascript - 为什么这里没有定义Vue?

javascript - Flash ExternalInterface 是否有等效于 removeCallback 的方法?

javascript - PHP/Javascript 中的文本修改

javascript - 使用渲染函数时如何在 Vue.js 模板中定义插槽?

javascript - HTTP请求删除记录,然后从数组中删除obj Vue.js