axios typeError:无法设置未定义的属性“用户名”

时间:2018-09-17 05:50:13

标签: vue.js axios

当我使用POSTMAN测试后端API时,一切正常,响应数据如下: {"username":"123","email":"123@gmail.com"}。然后,我使用axios来获取数据:

<template>
    <div>
        <h1>Welcome!</h1>
        <div>
            <b-button @click="getInfo()">Get your information</b-button>
            <h2 v-if="username !== ''">Your username is: {{ username }}</h2>
            <h2 v-if="email !== ''">Your email is: {{ email }}</h2>
        </div>
    </div>
</template>

<script>
import axios from 'axios'

export default {
    data () {
        return {
            username: '',
            email: ''
        }
    },
    methods: {
        getInfo () {
            axios.get('http://localhost:8088/api/information')
            .then(function (response) {
                this.username = response.data['username'];
                this.email = response.data['email'];
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
        }
    }
}
</script>

但是有一个错误typeError: Cannot set property 'username' of undefined。我对此感到困惑。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您应该在此处使用arrow function in es6 instead of function ()

示例:用(response)=>{代替function(response){

methods: {
      getInfo () {
          axios.get('http://localhost:8088/api/information')
          .then((response)=> {
              this.username = response.data['username'];
              this.email = response.data['email'];
              console.log(response);
        })
        .catch(function (error) {
              console.log(error);
        });
    }
}