Я пытаюсь отправить результаты опроса в свой API.
В Mounted() я делаю запрос GET
с помощью vue-resource
, получаю вопросы от моего дБ, а затем устанавливаю опросы. Чтобы отправить результаты, я пытался использовать this.$http.post
, в функции onComplete
SurveyJS, но у меня получилось 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.info(response);
UIkit.notification({
message: "Success",
pos: "top-center",
status: "success"
});
})
.catch(error => {
console.info(error);
UIkit.notification({
message: "Erro",
pos: "top-center",
status: "danger"
});
});
});
})
.catch(error => {
console.info(error);
UIkit.notification({
message: "Error",
pos: "top-center",
status: "danger"
});
});
}
Чтобы получить доступ к this
внутри параметра onComplete.add()
, вы можете заменить свою обычную функцию функцией стрелки:
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
, поэтому доступна внешняя.