2017-06-23 13 views
0

なぜAxiosのPOSTメソッドのコールバック応答で自分のデータにアクセスできないのかわかりません。

私はエラーサーバー応答にエラーメッセージを出力するためにここにしようとしているが、それはここに私のコードである「これは」
を定義されていないことをキャッチ誤差関数の中に書かれています:

VUEJS 2のAxios POSTメソッドで "this"にアクセスできない

<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コールバックの矢印機能を使用する必要があります。そうしないと、希望するバインディングが失われます。 2つのthenコールバック引数に関する

Promises/A+ specs, point 2.2.5指定:

onFulfilledonRejectedが関数として呼び出されなければならない(すなわち無this値)。厳密モードthisでは、3.2

3.2は、それらの内部undefinedあろう。スローモードでは、グローバルオブジェクトになります。

これは均等にthenの第2引数を使用するためだけの別の方法である、catchに適用されます。

だから書く:

.catch(error => { 
    console.log(this) // <-- problem solved. 
    this.errorBool = true 
    this.errorMessage = error 
    this.isNotAuth() 
}) 
関連する問題