【问题标题】:how to get data from DB using axios如何使用 axios 从数据库中获取数据
【发布时间】:2020-06-14 12:40:48
【问题描述】:

我遇到了问题。

我有我想要的项目列表,当我单击一个项目时,他将我带到另一个页面(组件)这是组件 ProjectDetail,当我可以找到该项目的详细信息时在其中,我有这段代码: 这是带我去其他组件的路线:

 {path: '/detail/:id', name: detail , component: detail },

我想从 DB w 获取带有 url 详细信息中的 id 的项目,但什么也没发生,这是 ProjectDetail.vue:

export default {
      data(){
      return{
      id: this.$route.params.id,
    projets:[],
   projet:{
    id:'',
   name:'',
     durre:'',
  description:'',
      budget:'',
  owner:'',
      }
   }
 },
      methods:{ 
    afficherProjets(){
       axios.get('api/getProjects/'+this.id)
         .then(data => {
           this.projets = data.data;
               });
                  }
           },
          mounted() {
           console.log('Component mounted.')
           this.afficherProjets();
        }
           }

这是我的控制器:

 public function getProjects($id)
{
   return Projet::findOrFail($id);
}

【问题讨论】:

  • 您是否在浏览器开发工具中检查了控制台中的任何 JavaScript 错误或您从 API 返回的 HTTP 响应中的任何错误?
  • 没有错误,他显示项目:开发工具中未定义
  • 您应该将{data} 替换为response 和console.log。我的猜测是,你应该使用this.project = data

标签: database laravel vue.js controller


【解决方案1】:

在你的 vue 中。

export default {
  data(){
   return{
    id: this.$route.params.id,
    projet:{}
  }
},
methods:{
 //GETID
 afficherProjet(){
   axios.get('api/getProject/'+this.id)
      .then(data => {
              this.projet = data.data;
           });
 }
},
mounted() {
  console.log('Component mounted.')
  this.afficherProjet();
}

路由 api.php 中的文件

//ALL
Route::get('getProjects', ['uses' =>'API\ProjetController@getProjects']);
//SPECIFIQ ID
Route::get('getProject/{id}', ['uses' =>'API\ProjetController@getProject']);

在你的控制器中,app/Http/API/ProjetController

public function getProjects()
{
   return Projet::latest()->paginate(15);
}

public function getProject($id)
{
  return Projet::findOrFail($id);
}

你的模型项目

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Projet extends Model
{
   public $timestamps = false;

   protected $table = 'projets';

   protected $fillable = [
     'name',
     'durre',
     'description',
     'budget',
     'owner'
   ];
}

你有你的模型吗?

您的错误来自“data.data”,因为它是空的,您应该调用“data”。

我个人更喜欢 Mounted。

我认为它现在可以工作了!

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-07-22
  • 2020-11-19
  • 2018-01-17
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 2023-01-21
相关资源
最近更新 更多