2017-06-23 28 views
0

我不明白为什么我无法在Axios的POST方法的回调响应中访问我的数据。

我想在这里打印错误服务器响应一个错误消息,但它说成“这”没有定义catch错误功能
这里是我的代码:

无法访问Axios中的“this”POST方法中的VUEJS 2

<template> 
<div class="row"> 
    <div class="form-group"> 
    <label for="exampleInputEmail1">Login</label> 
    <input type="text" v-model="loginForm" class="form-control" id="exampleInputEmail1" placeholder="login"> 
    </div> 
    <div class="form-group"> 
    <label for="exampleInputPassword1">Password</label> 
    <input type="password" v-model="passwordForm" class="form-control" id="exampleInputPassword1" placeholder="Password"> 
    </div> 
    <button @click="submitForm();" class="btn btn-default">Submit</button> 
    <div class="row" v-if="errorBool" style="color:red;"></div> 
</div> 
</template> 



<script> 
    import store from '../../store/store.js' 
    import Vuex from 'vuex' 
    import axios from 'axios' 
    export default { 
    store: store, 
    name: 'Login', 
    data() { 
     return { 
     msg: 'Welcome to Login page', 
     passwordForm: 'admin', 
     loginForm: 'admin', 
     errorBool: false, 
     errorMessage : '' 
     } 
    }, 
    computed: { 
    ...Vuex.mapGetters([ 
     'authentification' 
    ]), 
    }, 
    methods: { 
     ...Vuex.mapActions([ 
     'loadToken', 
     'isAuth', 
     'isNotAuth' 
     ]), 
     submitForm : function() { 

     axios.post('http://127.0.0.1:5000/login', { 
      name: this.loginForm, 
      password: this.passwordForm 
      }) 
      .then((response) => { 
      this.loadToken({token: response.data.token}) 
      this.isAuth() 
      this.$router.push('/dashboard') 
      this.errorBool = false 
      }) 
      .catch(function (error) { 
      console.log(this) // undefinided 
      this.errorBool = true 
      this.errorMessage = error 
      this.isNotAuth() 
      }) 
      } 
    }, 
    } 
</script> 

回答

2

就像你为then回调做了,你应该为catch回调使用箭头函数,否则你会失去所需的this绑定。

关于两个then回调参数的Promises/A+ specs, point 2.2.5规定了:

onFulfilledonRejected必须被称为函数(即没有0​​值)。 3.2

3.2即,在严格模式thisundefined他们的内部;在马虎模式下,它将成为全球性的对象。

这同样适用于catch,这仅仅是用于使用then的第二个参数的另一种方式。

所以写:

.catch(error => { 
    console.log(this) // <-- problem solved. 
    this.errorBool = true 
    this.errorMessage = error 
    this.isNotAuth() 
})