【问题标题】:How to get data by passing id into router from one vue component to another vue component through laravel axios如何通过laravel axios将id从一个vue组件传递到另一个vue组件的路由器来获取数据
【发布时间】:2020-07-14 16:12:46
【问题描述】:

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 p>

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');

这是我的控制器 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

【问题讨论】:

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


    【解决方案1】:

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

    应该是:

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

    【讨论】:

    • 我已经尝试过这一行但错误仍然显示``` {{ employee.name }} `` `
    • 是的。这里是 EmployeeDetails.vue 文件的 github 链接link
    • 您的错误中提到了/js/components/office/EmployeeProfile.vue,但我在您的仓库中没有看到此文件?
    • 兄弟。这不是 EmployeeProfile.vue。更正的是 EmployeeDetails.vue。再检查一遍
    • 其实我在axios中使用的是这样的`axios.get('api/details/'+this.$route.params.id) .then((data)=>{ this.employees = data.data; }) ` 但路线是这样的:localhost:8000/employee-details/api/details/2 这里有什么问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2019-02-20
    • 2020-03-23
    • 2021-06-27
    • 2019-10-10
    • 2018-02-19
    • 2018-07-15
    相关资源
    最近更新 更多