我正在尝试将 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/