簡體   English   中英

僅當用戶已登錄時顯示 div - Laravel Vue Inertia Jetstream

[英]Show div only if user has logged in - Laravel Vue Inertia Jetstream

我使用 Laravel Jetstream 創建了一個 webapp。 我也在使用 Vue 和 Inertia。 Jetstream 正在處理后端。 新用戶將登陸 Welcome.vue 並登錄后,他將進入 Dashboard.vue。 這是我的 web.php:

Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
])->group(function () {
    Route::get('/dashboard', function () {
        return Inertia::render('Dashboard', [
            'user' => Auth::user()
        ]);
    })->name('dashboard');
});

我只想在儀表板導航欄上顯示一條消息,例如“歡迎,姓名”。 這只是一個測試,因為我只想在不同的視圖中向授權用戶顯示幾個按鈕、文本和內容。

問題是,我的 Welcome 和 Dashboard 視圖幾乎相同,它們 95% 由組件組成。 它看起來像這樣:

<script setup>
import { Head, Link } from '@inertiajs/inertia-vue3';
import Main_w_side from '../Components/Custom/main_w_side.vue';
import Navabar from '../Components/Custom/Navabar.vue';
import Our_team from '../Components/Custom/OurTeam.vue';
import Portfolio from '../Components/Custom/Portfoglio.vue';
import CustomFooter from '../Components/Custom/CustomFooter.vue';
import { provide } from 'vue'


defineProps({
    canLogin: Boolean,
    canRegister: Boolean,
    laravelVersion: String,
    phpVersion: String,
});



</script>

<template>
<Head title="Dashboard v0.1"/>
<Navabar class="bg-white shadow dark:bg-gray-800" />
<Portfolio/>
<Main_w_side/>
<Our_team/>
<CustomFooter/>
</template>

因此 Dashboard 使用的 Navbar.vue 與 Welcome 使用的相同。 投資組合、Main_w_side、Our_team 等也是如此。

我知道我應該使用 v-if 方法

<p class="pl-12" v-if="loggedIn">You're logged in</p>

如果滿足某個條件,則顯示一個 div,但我沒有在網上找到任何指導,因為他們中的大多數都指的是刀片,或者是在沒有 Jetstream 的情況下制作的網絡應用程序(使用我目前沒有的用戶 controller)

我也在想,我或許應該使用 Provide/Inject 讓 web 應用程序中的每個組件都知道訪問的用戶是否已登錄。但我仍然不知道該怎么做。

我覺得必須有一個我不知道的行業標准,因為幾乎每個網站都需要這個功能(而不是重新創建整個頁面只是為了在某處有不同的 div)

按照默認的 InertiaJS 安裝,你應該能夠做這樣的事情:

v-if="$page.props.auth.user"

所以你的代碼應該是這樣的:

<p v-if="$page.props.auth.user" class="pl-12" v-if="loggedIn">You're logged in</p>

無需provide/inject ,您可以使用 inertia 的$page實例屬性或usePage()方法在每個組件上檢索經過身份驗證的用戶,無論該組件在組件樹中有多深。

正如@Abdullah Hejazy 提到的,在 Vue2 和 Vue3 中你可以簡單地做:

<p v-if="$page.props.auth.user" class="pl-12">You're logged in</p>

如果用戶未登錄, $page.props.auth.user將為 null。它來自HandleInertiaRequests中間件。

在 Vue3 中你也可以這樣做:

<script setup>
import { usePage, computed } from '@inertiajs/vue3'

const loggedIn = computed(() => {
   return !!usePage().props.auth.user
})
</script>

<template>
<p v-if="loggedIn" class="pl-12">You're logged in</p>
</template>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM