【问题标题】:How to get data by axios call in a mounted component?如何在挂载的组件中通过 axios 调用获取数据?
【发布时间】:2020-01-23 07:06:06
【问题描述】:

我正在通过使用 axios 执行 api 调用从 API 获取数据。但是我从 api 获取数据的尝试没有成功。如何让它发挥作用?

export default { 
    mounted() {
         this.fetchData()
    },
    data() {
       return {
         users:[]
    }    
  },

  methods: {
     fetchData(){
        axios.get('api/person')
              .then(response => (this.users= response.data))
              .catch(error => console.log(error));
      }
   }, 
}

在 ExampleComponent 中有这些行

<template>
 ...
 <div>{{users.name}}</div>
 <div>{{users.ip}}</div>
 ...
</template>

在 api.php 中

Route::get('/person', function() {
    $users = DB::table('user_info')->select('ip','name')->get();
     return $users;
 });

运行我做过的 php artisan tinker

 DB::table('user_info')->select('ip','name')->get();

我的所有数据都来自 DB(具有名称和 IP 的用户)。 在开发控制台中,我在响应选项卡中看到了我的数据。但在我的页面中什么都没有。

【问题讨论】:

  • 您遇到什么错误?
  • 显示错误日志
  • @tinwan 我没有错误也没有数据。
  • @Karan Sadana 未检测到可见错误。
  • 刷新页面后,你的 php 后端收到请求信息了吗?

标签: laravel vue.js axios


【解决方案1】:

你需要 v-for:

<div v-for="user in users">
 <div>{{user.name}}</div>
 <div>{{user.ip}}</div>
</div>

因此,您将为每个用户显示信息。

【讨论】:

  • 不客气。很高兴见到你。感谢您解决检查。
  • 我还有一个问题。这都是关于相同的代码,但我遇到的小问题。请检查一下如果你喜欢stackoverflow.com/questions/58063168/…
【解决方案2】:

vue有问题:模板中应该是{users.ip}和{users.name}。

【讨论】:

  • 我添加了这些行,但仍然没有获取数据。
【解决方案3】:

这就是我获取数据的方式。

<script>
  export default {
   data() {
     return {
       properties: []
      }
   },
   methods: {
     loadproperty(){
       axios.get('allhouses').then(response => this.properties = response.data);
      },
   },
   mounted() {
    this.loadproperty();
    }
   }

</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 2021-09-24
    • 2019-06-21
    • 2020-12-15
    • 1970-01-01
    • 2020-11-19
    • 2020-07-25
    • 2020-07-17
    相关资源
    最近更新 更多