Vue.JS 是否适用于 AJAX http 调用?

编程入门 行业动态 更新时间:2024-10-27 08:24:53
本文介绍了Vue.JS 是否适用于 AJAX http 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从我的 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.该帖子运行良好,我确实在 .then() 承诺中得到了响应.

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.

但是,尝试执行诸如 this.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 调用?

本文发布于:2023-11-24 19:24:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626503.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:适用于   JS   Vue   AJAX   http

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!