Laravel 5.7 - 如何使用axios.get从API检索数据?

问题描述 投票:2回答:3

我正在尝试从Laravel Vue组件中的API获取数据。我在控制台中收到此错误:

TypeError:无法设置undefined的属性'continents'

我错过了什么?

这是我的代码:

<script>
    export default {
        mounted() {
            console.log('Component mounted.');
        },
        created(){
            this.loadData();
        },
        data() {  
            return {
                continents: [],
            }
       },
       methods: {
            loadData: function() {
                axios.get('/api/continents')
                  .then(function (response) {
                    // handle success
                    console.log(response.data);
                    this.continents = response.data;
                  })
                  .catch(function (error) {
                    // handle error
                    console.log(error);
                  })
                  .then(function () {
                    // always executed
                  });
            },       
        },  
    }
</script>
laravel laravel-5 vue.js
3个回答
4
投票

这是axios.get请求的简单工作演示

var app = new Vue({
  el: '#app',
  data: {
    users:[]
  },
  mounted(){
     this.loadData();
  },
  methods:{
     loadData:function(){
  axios.get('https://jsonplaceholder.typicode.com/users').then(res=>{
       if(res.status==200){
         this.users=res.data;
       }
     }).catch(err=>{
         console.log(err)
     });
     }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
 <ol>
    <li v-if="users.length>0" v-for="user in users">
      {{ user.name }}
    </li>
  </ol>
</div>

1
投票

在方法中,您必须在回调函数中使用箭头函数语法,以保持您的数据属性可访问。当您使用正常语法声明函数时,您添加一个“子范围”,并且回调函数中的this.components在您的回调函数中引用“this”。

将您的方法更改为:

loadData() {
            axios.get('/api/continents')
              .then((response) => {
                // handle success
                console.log(response.data);
                //now this refers to your vue instance and this can access you data property
                this.continents = response.data;
              })
              .catch((error) => {
                // handle error
                console.log(error);
              })
              .then(() => {
                // always executed
              });
        },  

1
投票

你应该在你的调用中使用箭头函数,因为你的.then函数中没有这个实例.Hence尝试如下。

阅读更多关于箭头功能here的信息。

methods: {
        loadData: function() {
            axios.get('/api/continents')
              .then((response) => {
                // handle success
                console.log(response.data);
                this.continents = response.data;
              })
              .catch(function (error) {
                // handle error
                console.log(error);
              })
              .then(function () {
                // always executed
              });
        },       
    },  
© www.soinside.com 2019 - 2024. All rights reserved.