首页 > 解决方案 > 需要在 vue.js 前端和 Laravel 后端打印名称而不是 id

问题描述

这是我的 CategoryController.php 代码...

public function name($id) {
    $f = Category::findOrFail($id);
    $nm = $f->name;
    return $nm;
}

这是我的路由器。

Route::get('/category/{id}', [CategoryController::class, 'name']);

在 vue.js 我在方法中定义了这个,

async getCategoryName($id){
            await this.callApi('get','/category/' + $id)
            .then(response => {
                this.name = response.data.name
                return this.name;
            });
    }

在表中,我需要获取类别名称而不是类别 ID。从 URL 我得到类别名称,但它表明 [object promise]

                    <table class="_table">
                            <!-- TABLE TITLE -->
                        <tr>
                            <th>ID</th>
                            <th>Category Name</th>
                            <th>Name</th>
                            <th>Created At</th>
                            <th>Action</th>
                        </tr>
                            <!-- TABLE TITLE -->

                            <!-- ITEMS -->
                        <tr v-for="(tag, i) in tags" :key="i" if="tags.length">
                            <td>{{tag.id}}</td>
                            <td>{{getCategoryName(tag.categoryId)}}</td>
                            <td class="_table_name">{{tag.name}}</td>
                            <td>{{tag.created_at}}</td>
                            <td>
                                <Button type="info" size="small" @click="showEditModal(tag, i)">Edit</Button>
                                <Button type="error" size="small" @click="showDeletingModal(tag, i)" :loading="tag.isDeleting">Delete</Button>
                            </td>
                        </tr>
                    </table>

请帮我...

标签: laravelvue.jsvue-componentvue-routerlaravel-8

解决方案


这是 vue.js 的正常行为,为什么不在控制器中添加类别名称而不是在服务器端加载它,您的方法在性能方面并不好。

在您获得视图的控制器中,您将拥有以下内容:$tags = Tag::all() 您可以简单地加载每个类别:$tags = Tag::with('category')->get()

在您的 vue 应用程序中,您可以简单地访问名称,例如:tag.category.name


推荐阅读