javascript - 无法在 VUEJS 2 中的 Axios POST 方法中访问 "this"

标签 javascript vue.js axios

我不明白为什么我在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>

最佳答案

就像你为 then 回调所做的那样,你应该为 catch 回调使用箭头函数,否则你会丢失所需的 this绑定(bind)。

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

onFulfilled and onRejected must be called as functions (i.e. with no this value).3.2

3.2 That is, in strict mode this will be undefined inside of them; in sloppy mode, it will be the global object.

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

这样写:

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

关于javascript - 无法在 VUEJS 2 中的 Axios POST 方法中访问 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44715661/

相关文章:

javascript - 如何完全停止 d3.zoom?

Javascript getElementByID().innerHTML() 不工作

javascript - 将事件监听器添加到具有特定类的当前和 future 元素

javascript - Vue - 检查用户是否离线,然后在他们恢复在线后显示一秒钟的 div

javascript - Chrome 和 IE8 对比其他

javascript - 使用 ids 进行 Google 知识图谱搜索

javascript - 带有 Content-Disposition 的 HTTP 响应不会触发下载

laravel - 为什么我的下载功能(使用 Vue JS 和 Laravel 创建)会导致文件损坏?

node.js - axios无法从另一个localhost获取json数据

javascript - 测试执行期间Vue警告