【问题标题】:Cannot access "this" in Axios POST method in VUEJS 2无法在 VUEJS 2 的 Axios POST 方法中访问“this”
【发布时间】:2017-11-26 16:37:59
【问题描述】:

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

我在这里尝试在错误服务器响应上打印一条错误消息,但它在 catch 错误函数中说“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>

【问题讨论】:

    标签: javascript vue.js axios


    【解决方案1】:

    就像您对then 回调所做的那样,您应该为catch 回调使用箭头函数,否则您将失去所需的this 绑定。

    Promises/A+ specs, point 2.2.5 指定了两个 then 回调参数:

    onFulfilledonRejected 必须作为函数调用(即没有 this 值)。3.2

    3.2也就是说,在严格模式下this将是undefined在其中;在草率模式下,它将是全局对象。

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

    所以写:

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

    【讨论】:

      猜你喜欢
      • 2019-08-04
      • 1970-01-01
      • 2012-06-17
      • 2015-05-25
      • 1970-01-01
      • 2023-03-23
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多