You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue前端展示Laravel模型返回的用户在线状态?

实现Laravel用户在线状态传递到Vue前端表格展示

步骤1:在UserResource中添加在线状态字段

控制器返回的是UserResource,需要在资源类里把模型的isOnline()结果加入返回数据,这样前端就能直接拿到在线状态:

// app/Http/Resources/UserResource.php
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'last_online_at' => $this->last_online_at,
        'is_online' => $this->isOnline(), // 新增该字段,传递在线状态
        // 其他原有字段...
    ];
}

步骤2:调整Vue模板与逻辑

前端拿到的用户数据会包含is_online字段(布尔值),直接用条件渲染显示对应的状态标签即可,无需复杂计算属性:

<td>
    <span class="badge badge-warning">{{ user.last_online_at }}</span>
</td>
<td>
    <span v-if="user.is_online" class="badge badge-success">Online</span>
    <span v-else class="badge badge-danger">Offline</span>
</td>

同时可以删除原来的getOnlineStatus计算属性,简化逻辑:

methods: {
    getUsers() {
        axios.post(`/admin/users/getusers?page=${this.pagination.current_page}`, {
            perPage: this.displayRecord
        })
        .then(response => {
            this.users = response.data.data;
        })
        .catch(err => console.error('获取用户列表失败:', err));
    }
}

额外优化(可选)

由于缓存1分钟后过期,可在前端添加定时刷新,保证状态实时性:

mounted() {
    this.getUsers();
    // 每1分钟刷新一次用户列表
    this.refreshTimer = setInterval(() => this.getUsers(), 60000);
},
beforeUnmount() {
    // 组件销毁时清除定时器
    clearInterval(this.refreshTimer);
}

内容的提问来源于stack exchange,提问作者Maison012

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:25:21