如何通过laravel axios将id从路由器从一个vue组件传递到另一个vue组件来获取数据

时间:2020-04-02 15:58:01

标签: laravel vue.js error-handling vue-component vue-router

Employee.vue组件

<tr role="row" class="odd" v-for="(employee, index) in employees" :key="index">
   <td>{{ index+1 }}</td>
   <td><router-link :to="/employee-profile/+employee.id">{{ employee.name }}</router-link></td>
</tr>

我要通过 app.js 中的路由从此处将员工 id 发送到 EmployeeDetails.vue >

let routes = [
    { path: '/employee', component: require('./components/office/Employee.vue').default },
    { path: '/employee-details/:id', component: require('./components/office/EmployeeDetails').default },
]

这是我的EmployeeDetails.vue组件

<script>
    export default {
        data() {
            return {
                employees:{},
            }
        },
        mounted() {
            let id = this.$route.params.id

            axios.get('api/employee-details/'+id)
                  .then(response => {
                      this.employees = response.data;
                  });
        }
    }
</script>

这是我称为通过API资源路由的 api.php 文件

Route::get('employee-details/{id}', 'API\EmployeeController@employeeDetails');

这是我的Controller EmployeeController.php,我在其中调用了返回数据的功能

public function employeeDetails($id)
{
   return DB::table('employees')->where('id', $id)->get(); 
}

但是问题是:我的 控制台 中没有显示数据并返回错误消息。错误在下面给出。其实我想要如何解决这个错误。

app.js:81221 [Vue warn]: Error in render: "TypeError: Cannot read property '0' of undefined"

found in

---> <EmployeeProfile> at resources/js/components/office/EmployeeProfile.vue
       <Root>
app.js:82484 TypeError: Cannot read property '0' of undefined

1 个答案:

答案 0 :(得分:0)

您在路由器链接中传递的ID似乎不正确。

应该是:

<router-link :to="`/employee-profile/${employee.id}`">{{ employee.name }}</router-link>