Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

javascript - Using Axios in VueJS - this undefined

Using typescript and vuejs + axios, i have the following .catch function on a post request - I'm attempting to trap some network errors and report status to the end user:

      .catch(function(error) {
          console.error(error.response);
          if ( error.message === "Network Error" ) {
              this.alert.show = 1;
              this.alert.message = error.message + ': Please try again later';
          }
      });

this.alert.show throws "this" undefined in the debugger. Is this a problem with javascript/typescript and exception handlers in general, or is this a bug in Axios or a design decision I can't find documentation for?

And is there a way for me to communicate this back to my component absent a "this" reference?

Full block:

export default {
  data() {
    return {
      form: {
        email: '',
        password: '',
      },
      alert: {
          show: 0,
          message: '',
      },
    };
  },
  methods: {
    onSubmit(evt) {
      evt.preventDefault();

      if (this.form.password.length > 0) {
          // TODO: Hideous workaround for .catch().
          let that = this;
          this.$http.post('http://localhost:3000/login', {
              email: this.form.email,
              password: this.form.password,
          })
          .then((response) => {
              const is_admin = response.data.user.is_admin;
              localStorage.setItem('user', JSON.stringify(response.data.user));
              localStorage.setItem('jwt', response.data.token);

              if (localStorage.getItem('jwt') != null) {
                  this.$emit('loggedIn');
                  if (this.$route.params.nextUrl != null) {
                      this.$router.push(this.$route.params.nextUrl);
                  } else {
                      if (is_admin === 1) {
                          this.$router.push('admin');
                      } else {
                          this.$router.push('dashboard');
                      }
                  }
              }

          })
          .catch((error) => {
                console.error(error);
                if ( error.message === 'Network Error' ) {
                    this.alert.show = 10;
                    this.alert.message = error.message + ': Please try again later';
                }
          });
      }
    },
    onReset(evt) {
      evt.preventDefault();
      /* Reset our form values */
      this.form.email = '';
      this.form.password = '';
      /* Trick to reset/clear native browser form validation state */
      this.show = false;
      this.$nextTick(() => { this.show = true; });
    },
  },
};

Vue template (Login.vue):

<template>
<div>
<b-container class="loginPage">
  <b-row>
    <b-col sm="4"/>
    <b-col sm="4">
      <b-form @submit="onSubmit" @reset="onReset">
         <h2>Login</h2>
         <p>Please enter your email and password</p>
         <b-form-input id="exampleInput1"
                      type="email"
                      v-model="form.email"
                      required
                      placeholder="Enter email">
         </b-form-input>
         <b-form-input id="exampleInput2"
                      type="password"
                      v-model="form.password"
                      required
                      placeholder="Enter password">
         </b-form-input>
      </b-form-group>

        <div class="forgot">
        <a href="reset.html">Forgot password?</a>
        </div>

      <b-button class="btn-primary" type="submit" variant="primary">Submit</b-button>
      <b-button class="btn-reset"   type="reset" variant="danger">Reset</b-button>

      <b-alert :show="alert.show" variant="danger">
         {{alert.message}}
      </b-alert>
    </b-form>

    </b-col>
    <b-col sm="4"/>
  </b-row>
</b-container >


    </div>
</template>

Also using https://bootstrap-vue.js.org.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're creating a new local function scope. Use fat arrow instead.

.catch((error) => {
      console.error(error.response);
      if ( error.message === "Network Error" ) {
          this.alert.show = 1;
          this.alert.message = error.message + ': Please try again later';
      }
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...