Vue.JS是否可以与AJAX http调用一起使用? [英] Does Vue.JS work with AJAX http calls?
问题描述
我正在尝试通过HTML执行以下操作:
I am trying to do the following from my HTML:
var vm = new Vue({
el: '#loginContent',
data: {
main_message: 'Login',
isLoggedIn: false,
loginError: '',
loginButton:'Login'
},
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
});
基本上用户按下登录按钮,调用了onLogin方法,该方法将帖子发送到我的API。
Basically user presses the login button, onLogin method is called that sends a post to my API. The post is working fine and I do get the response back in the .then() promise.
但是,尝试做这样的事情。 isLoggedIn = true;
不会用用户期望的HTML更新用户的DOM。
But, trying to do things like this.isLoggedIn = true;
does not update my DOM with what I am expecting the HTML to do when the user logs in.
可能是因为我当我在promise中得到响应并且找不到 vm实例时,我是否处于某种后台线程中(抱歉,移动开发人员在这里)?
Could be that I am in some sort of background thread (sorry, mobile developer here) when I get the response in the promise and it can't find the "vm" instance?
谢谢
推荐答案
可能是因为您的 this
指向错误而发生作用域,此作用域在 $。ajax
调用内更改,因此您只需要执行以下操作:
It is probably happening because your this
is not pointing to correct scope, scope of this changes inside an $.ajax
call, so you just have to do something like following:
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
var that = this
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
that.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
that.isLoggedIn = true;
} else {
that.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
这篇关于Vue.JS是否可以与AJAX http调用一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!