简体   繁体   中英

How can I update a data value from a method inside a promise with vue.js?

My component script is:

export default {
  name: "Authenticate",
  data: () => {
    return {
      validationFailed: {}
    };
  },
  methods: {
    validateForm() {
      this.validationFailed = {};
      if (this.createEmail.trim().length === 0) {
        this.validationFailed.createEmailField = "Email cannot be blank. ";
      }

      if (this.createPassword.trim().length === 0) {
        this.validationFailed.createPasswordField =
          "Password cannot be blank. ";
      }

      if (Object.keys(this.validationFailed).length === 0) {
        return true;
      }

      return false;
    },
    handleSubmit() {
      const that = this;
      axios
        .request({
          url: `${process.env.VUE_APP_API_URL}/users`,
          method: "POST",
          data: {
            email: this.createEmail,
            password: this.createPassword
          }
        })
        .then(response => {
          console.log(response);
        })
        .catch(err => {
          that.validationFailed.createEmailField = "something";
        });
    }
  }
};

But inside the catch, with a debugger , I can see that the value gets set. But in my template , the validationFailed doesn't get updated. What am I doing wrong?

It's Vue reactivity problem. You need to assign this.validationFailed to new object. You can try ES6 syntax in catch block:

that.validationFailed = {
    ...that.validationFailed,
    createEmailField: 'something'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM