Vue.JS是否支持AJAX http调用?
问题描述:
我试图做从我的HTML如下:Vue.JS是否支持AJAX http调用?
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。该帖子工作正常,我确实收到了.then()承诺中的回复。
但是,试图做这样的事情this.isLoggedIn = true;
不与我所期待的HTML时做英寸
用户登录可能是我在某种后台线程(对不起更新我的DOM,移动开发者在这里),当我得到承诺的答复,它无法找到“VM”实例?
感谢
答
它可能发生,因为你的this
没有指向正确的范围,在此范围内的$.ajax
调用内部的变化,所以你就必须这样做以下:
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);
});
}
}
答
我会提出另一种使用ES6箭头函数的方法,如'=>'。它很简单,不需要额外的变量。如下所示:
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then((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);
});
是的,就是这样。谢谢yiu =] –