当我使用POSTMAN测试后端API时,一切正常,响应数据看起来像:{"username":"123","email":"[email protected]"}
。然后我用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
。我很困惑。有人可以帮忙吗?
你应该在这里使用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);
});
}
}