开发者问题收集

Vue-无法在响应中设置未定义的属性

2020-07-11
1366
<template>
<div class="address">
  <h1>{{address}}</h1>
</div>
</template>

<script>

export default {
    data() {
        return {
            id: this.$route.params.id,
            address:''
    }
},
created(){
 this.$axios.post("http://localhost/flutter_api/action.php",{
   id: this.id,
   action: "fetchaddress"
 })
 .then(function(res) { 
    console.log(res.data.address); // This returns the address
    alert(res.data.address);
    this.address=res.data.address;
 })
 .catch(function(error){
    console.log(error)
 })
 }
 }
 </script>

它在 eval (Address.vue?b0a0:24) 处抛出如下错误 TypeError: Cannot set property 'address' of undefined``

请帮帮我

1个回答

这是因为您没有在 http 调用的回调中绑定 this 。您可以使用箭头函数来解决它。

 .then(function(res) { 
    console.log(res.data.address); // This returns the address
    alert(res.data.address);
    this.address=res.data.address;
 })

 .then((res) => { 
    console.log(res.data.address); // This returns the address
    alert(res.data.address);
    this.address=res.data.address;
 })
Raffobaffo
2020-07-11