首页 > 解决方案 > 如何在vue中取一个user_id并找到用户名

问题描述

我有这个数据数组,

[ {“id”:6,“log_name”:“默认”,“description”:“Eliminado”,“subject_id”:12,“subject_type”:“App\Models\DiscussionForum”,“causer_id”:1,“causer_type ": "App\Models\User", "properties": [], "created_at": "2019-11-20 09:30:30", "updated_at": "2019-11-20 09:30:30" }]

用户 id 是被调用的causer_id,我该如何使用它并显示用户名?

这是在表内的 vue.js 文件中完成的

<el-table
    :data="logs"
    label-width="120px"
    height="550">
    <el-table-column
        width="150"
        label="Fecha">
        <template slot-scope="scope">
            {{ formatDate(scope.row.created_at) }}
        </template>
    </el-table-column>
    <el-table-column
        label="Accion">
        <template slot-scope="scope">
            {{'El ' + formatModel(scope.row.subject_type)
            + ' con id: ' + scope.row.subject_id
            + ' ha sido ' + scope.row.description}}
        </template>
    </el-table-column>
    <el-table-column
        label="Hecho por">
        <template slot-scope="scope">
            {{scope.row.causer_id}}
        </template>
    </el-table-column>
</el-table>

有没有办法可以创建一个函数并将其传递给 id 并返回用户名?

标签: vue.js

解决方案


您需要创建一个获取用户名的方法。然后,您将在 Laravel 中创建一个路由,该路由将根据您刚刚传递的 id 返回该用户的查询并返回该用户。

在 Vue 组件内的表格中:

<el-table
    :data="logs"
    label-width="120px"
    height="550">
    ...
    <el-table-column
        label="Hecho por">
        <template slot-scope="scope">
            {{displayUserName(scope.row.causer_id)}}
        </template>
    </el-table-column>
</el-table>

在您的 Vue 组件中:

 data: { userNames: []      },
 mounted() {
        this.getUserNames();
    },
 methods: {
    getUserNames() {
       $.each(this.users, function (index, user))
       {
            this.getUserName(user.id);
       }
    },
    displayUserName(userId)
    {
       return this.userNames.userId;
    },
    getUserName(userId) {
            this.$http.get('/user/'+userId)
                .then(response => {
                        this.userNames.userId = response.data.name;
                    }
                );
        },

在你的 laravel 路由文件中

 Route::get('/user/{userId}', 'UserController@view')

在您的 laravel UserController 文件中

public function view($userId)
{
    $user = User::findOrFail($userId);
    return $user;
}

推荐阅读