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

Fel*_*das 2 ajax vue.js

我正在尝试从我的 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);
          });
        }
      }
    });
Run Code Online (Sandbox Code Playgroud)

基本上用户按下登录按钮,调用 onLogin 方法将帖子发送到我的 API。该帖子运行良好,我确实在 .then() 承诺中得到了响应。

但是,this.isLoggedIn = true;当用户登录时,尝试做的事情不会像我期望的 HTML 那样更新我的 DOM。

可能是我在某种后台线程中(对不起,这里是移动开发人员),当我在承诺中得到响应并且找不到“vm”实例时?

谢谢

Sau*_*abh 6

这可能是因为您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);
      });
    }
  }
Run Code Online (Sandbox Code Playgroud)