使用Vue和Sweetalert形成警报而不注册Vue商店?

时间:2019-06-27 01:49:39

标签: vue.js sweetalert

我有一个简单的登录表单,该表单带有一个按钮,该按钮默认情况下具有一个反应性文本{{ msg }},其显示为log in,而当用户发送该表单时,它将更改为logging...。如果表单失败,那么我想说send again

我正在使用sweetalert发出警告,并且打算更改sweetAlert内部的msg数据。但是由于某种原因,它将undefined返回到this.msg

html

<form id="login_form">
 <input class="form-control" type="text" required="" name="email" placeholder="Email">
 <input class="form-control" type="password" required="" name="password" placeholder="Password">
 <button class="btn" type="submit">Log In</button>
</form>

JavaScript

export default {
 data() {
   return {
     msg: "Log in"
    }
  },
methods: {
submitForm() {
  const loginData = $("#login_form").serializeArray();
  const v = this;
  this.msg = "logging..."
  $.ajax({
    url: "/authentication",
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    data: JSON.stringify({
      strategy: "local",
      email: loginData[0].value,
      password: loginData[1].value
    }),
    success: function (data) {
      window.location.replace("/");
       this.msg = "logged!"
    },
    error: function (error) {
      if (error.status === 401) {
        swal("Wrong email or password");
        this.msg = "Try again?";
        console.log("this.msg) //returns undefined
      } else if (error.status === 400) {
        swal("Wrong email or password");
        this.msg = "Try again?";
      } else {
        swal("Error. Try again!");
        this.msg = "Try again?";
      }
    }
  });
}
}

我也尝试了promises,但是它也返回this.msg作为未定义。

如果我在sweetAlert中console.log(this.msg)返回未定义。

1 个答案:

答案 0 :(得分:1)

我怀疑它的上下文行为。试试这个

export default {
 data() {
   return {
     msg: "Log in"
    }
  },
methods: {
submitForm() {
  const self = this;
  const loginData = $("#login_form").serializeArray();
  const v = this;

  self.msg = "logging..."
  $.ajax({
    url: "/authentication",
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    data: JSON.stringify({
      strategy: "local",
      email: loginData[0].value,
      password: loginData[1].value
    }),
    success: function (data) {
      window.location.replace("/");
       self.msg = "logged!"
    },
    error: function (error) {
      if (error.status === 401) {
        swal("Wrong email or password");
        self.msg = "Try again?";
        console.log(self.msg) //returns undefined
      } else if (error.status === 400) {
        swal("Wrong email or password");
        self.msg = "Try again?";
      } else {
        swal("Error. Try again!");
        self.msg = "Try again?";
      }
    }
  });
}
}
相关问题