Dynamically create the items of a NavBar #11649
-
I have a Navbar.vue component where I am attempting to create the Links dynamically:
Basically, I want to have the The issue I have now is that I render the page, it shows Then I logout and it keep showing How can I dynamically change the computed |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
so what about using <script setup>
import { Link, usePage } from '@inertiajs/vue3';
import { ref, computed, watch } from 'vue';
import Dropdown from '@/Components/Dropdown.vue';
import { IconSun, IconMoonStars, IconDeviceDesktopCog } from '@tabler/icons-vue';
const page = usePage();
const isAuthenticated = computed(() => !!page.props.auth.user);
const user = computed(() => page.props.auth.user);
const baseNavbarLinks = computed(() => [
{ name: 'Home', route: 'home' },
{ name: 'About', route: 'about' },
{ name: 'Contact', route: 'contact' },
]);
const authNavbarLinks = computed(() => [
{ name: user.value?.name || 'User', route: 'dashboard' },
{ name: 'Logout', route: 'logout' },
]);
const notAuthNavbarLinks = computed(() => [
{ name: 'Login', route: 'login' },
{ name: 'Register', route: 'register' },
]);
const navbarLinks = ref([]);
const updateNavbarLinks = () => {
navbarLinks.value = [
...baseNavbarLinks.value,
...(isAuthenticated.value ? authNavbarLinks.value : notAuthNavbarLinks.value)
];
};
watch(isAuthenticated, updateNavbarLinks, { immediate: true });
watch(user, updateNavbarLinks);
</script>
<template>
<nav class="bg-white border-gray-200 dark:bg-bluegray-dark z-50">
<div class="max-w-screen-xl flex flex-wrap items-center justify-between mx-auto p-4">
<a href="/" class="flex items-center space-x-4 rtl:space-x-reverse">
<img src="https://flowbite.com/docs/images/logo.svg" class="h-8" alt="Flowbite Logo" />
<span class="self-center text-2xl font-semibold whitespace-nowrap dark:text-white">Title</span>
</a>
<div class="flex items-center space-x-4 rtl:space-x-reverse">
<Link
v-for="link in navbarLinks"
:key="link.name"
:href="route(link.route)"
class="inline-flex items-center font-medium justify-center cursor-pointer dark:text-white hover:underline text-gray-900 pb-1"
>
{{ link.name }}
</Link>
</div>
</div>
</nav>
</template> |
Beta Was this translation helpful? Give feedback.
so what about using
watch
here to keep an eye on the auth state and update the links when it changes? Something like this: