首页 > 解决方案 > 如何在 Laravel 中的 Vue 组件的登录页面上显示用户被禁止的消息

问题描述

所以我在 Laravel 中使用这个中间件来检查用户是否被阻止,然后如果他们被阻止则将其注销:

class IsUserBanned
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (auth()->check() && auth()->user()->banned_until != null) {

            if (auth()->user()->banned_until == 0) {
                $message = 'Your account has been banned permanently.';
            }
            if (now()->lessThan(auth()->user()->banned_until)) {
                $banned_days = now()->diffInDays(auth()->user()->banned_until) + 1;
                $message = 'Your account has been suspended for ' . $banned_days . ' ' . Str::plural('day', $banned_days);
            }

            return redirect()->route('login')->with(auth('web')->logout())->with('message', $message);
        }

        return $next($request);
    }
}

我知道要在blade.php中显示消息我会使用这样的东西:

<div class="card-body">
 
    @if (session('message'))
        <div class="alert alert-danger">{{ session('message') }}</div>
    @endif
 
    <form method="POST" action="{{ route('login') }}">

我的问题是如何在 Vue 组件中做同样的事情?v-if 会起作用吗?如果这是一个愚蠢的问题,我是 Vue 的新手,很抱歉......

编辑:: 我的猜测是这样的,但它不起作用

<div v-if="message" class="mb-4 font-medium text-sm text-red-600">
   {{ message }}
</div>

谢谢。

标签: laravelvuejs2inertiajsjetstream

解决方案


默认情况下,Vue 无法访问 Laravel 会话状态,因为这可能会导致信息泄露。像你提议的东西(使用v-if指令来显示消息)起作用,但你仍然必须以某种方式将消息传递给前端。

如果你使用Laravel JetstreamInertia和 Vue,你可以简单地将会话的message元素作为 Vue 道具传递给你的前端。

在您的 Vue 组件中(如果您使用的是单文件组件,它将在一个*.vue文件中),您需要将其添加到您的 props 数组中,如下所示:

// template up here ...

export default {
  data() { ... },
  props: ['message'] // add to this array
  // ...
}

然后,当您在 Laravel 端渲染惯性响应时,您需要传递道具。如果你按照你的login路线走,你最终会找到一个电话Inertia::renderinertia(...)助手。您可以将会话添加到那里的属性数组中,如下所示:

// probably in routes/web.php

Route::get('/login', function() {
  // more code ...

  Inertia::render('Login', [ 'message' => session('message') ]);
}); 

这是您将属性传递到页面的一般方法,但是,如果您使用 Laravel Fortify 通过 Jetstream 的启动器提供的未自定义的默认登录视图,则需要采取额外的步骤:

  • 您正在编辑的 Vue SFC 可能位于resources/js/Pages/Auth/Login.vue
  • 呈现该页面的惯性响应通常由框架自动处理。要对其进行自定义,您需要遵循这些说明并使用看起来更接近此的代码:
Fortify::loginView(function () {
    return Inertia::render('Auth/Login', [
        'message' => session('message')
    ]);
});

推荐阅读