Skip to content
TheChatArchiveThe Chat Archive
Grok 4.1 Fast· xaiHugging Face Frontier Reasoning Traces

Implement complex routing with guards and nested views in a Vue.js app.

  1. User

    Implement complex routing with guards and nested views in a Vue.js app.

  2. Assistant
    <!-- App.vue -->
    <template>
      <div id="app">
        <nav>
          <router-link to="/">Login</router-link>
          <router-link v-if="isAuthenticated" to="/dashboard">Dashboard</router-link>
          <router-link v-if="isAuthenticated" to="/dashboard/profile">Profile</router-link>
          <router-link v-if="isAuthenticated" to="/dashboard/settings">Settings</router-link>
          <a v-if="isAuthenticated" href="#" @click.prevent="logout">Logout</a>
        </nav>
        <router-view />
      </div>
    </template>
    
    <script setup>
    import { computed } from 'vue'
    import { useRouter, useAuthStore } from './stores/auth' // Pinia store for auth (see below)
    
    const router = useRouter()
    const authStore = useAuthStore()
    
    const isAuthenticated = computed(() => authStore.isAuthenticated)
    
    const logout = () => {
      authStore.logout()
      router.push('/login')
    }
    </script>
    
    <style>
    nav { padding: 20px; background: #f5f5f5; }
    nav a { margin-right: 10px; text-decoration: none; }
    router-view { padding: 40px; }
    </style>
    
    // router/index.js
    import { createRouter, createWebHistory } from 'vue-router'
    import { useAuthStore } from '../stores/auth.js'
    import Login from '../views/Login.vue'
    import Dashboard from '../views/Dashboard.vue'
    import Profile from '../views/Profile.vue'
    import Settings from '../views/Settings.vue'
    import Admin from '../views/Admin.vue'
    import NotFound from '../views/NotFound.vue'
    
    const router = createRouter({
      history: createWebHistory(import.meta.env.BASE_URL),
      routes: [
        {
          path: '/',
          redirect: '/login'
        },
        {
          path: '/login',
          name: 'login',
          component: Login,
          meta: { requiresGuest: true } // Guard: only for non-auth users
        },
        {
          path: '/dashboard',
          name: 'dashboard',
          component: Dashboard,
          meta: { requiresAuth: true }, // Guard: requires auth
          children: [ // Nested routes
            {
              path: '', // Default child
              name: 'dashboard-home',
              component: Profile // Or a Home component
            },
            {
              path: 'profile/:id?', // Dynamic segment, optional
              name: 'profile',
              component: Profile,
              props: true // Pass route params as props
            },
            {
              path: 'settings',
              name: 'settings',
              component: Settings,
              meta: { requiresAdmin: true } // Per-route guard
            }
          ]
        },
        {
          path: '/admin',
          name: 'admin',
          component: Admin,
          meta: { requiresAuth: true, requiresAdmin: true }
        },
        {
          path: '/:pathMatch(.*)*', // Catch-all for 404
          name: 'NotFound',
          component: NotFound
        }
      ]
    })
    
    // Global navigation guards
    router.beforeEach(async (to, from, next) => {
      const authStore = useAuthStore()
      await authStore.checkAuth() // Load auth state (e.g., from localStorage)
    
      if (to.meta.requiresAuth && !authStore.isAuthenticated) {
        return next({ name: 'login', query: { redirect: to.fullPath } }) // Redirect with return URL
      }
    
      if (to.meta.requiresGuest && authStore.isAuthenticated) {
        return next({ name: 'dashboard' }) // Redirect auth users away from login
      }
    
      if (to.meta.requiresAdmin && !authStore.isAdmin) {
        return next({ name: 'dashboard' }) // Insufficient perms
      }
    
      next()
    })
    
    // Per-route enter guard example (in Dashboard.vue we'll add one too)
    router.beforeResolve((to, from, next) => {
      console.log(`Entering route: ${to.name}`)
      next()
    })
    
    router.afterEach((to) => {
      document.title = to.meta.title || `${to.name} - Vue App`
    })
    
    export default router
    
    <!-- views/Login.vue -->
    <template>
      <div>
        <h1>Login</h1>
        <form @submit.prevent="login">
          <input v-model="email" type="email" placeholder="Email" required />
          <input v-model="password" type="password" placeholder="Password" required />
          <button type="submit">Login</button>
        </form>
        <p v-if="$route.query.redirect">Redirecting to: {{ $route.query.redirect }}</p>
      </div>
    </template>
    
    <script setup>
    import { ref } from 'vue'
    import { useRouter } from 'vue-router'
    import { useAuthStore } from '../stores/auth.js'
    
    const router = useRouter()
    const authStore = useAuthStore()
    
    const email = ref('')
    const password = ref('')
    
    const login = async () => {
      // Simulate API call
      if (email.value === 'user@example.com' && password.value === 'password') {
        await authStore.login({ email: email.value, isAdmin: false })
        const redirect = router.currentRoute.value.query.redirect || '/dashboard'
        router.push(redirect)
      } else if (email.value === 'admin@example.com' && password.value === 'admin') {
        await authStore.login({ email: email.value, isAdmin: true })
        router.push('/dashboard/settings')
      } else {
        alert('Invalid credentials')
      }
    }
    </script>
    
    <!-- views/Dashboard.vue (Nested router-view) -->
    <template>
      <div>
        <h1>Dashboard</h1>
        <p>Welcome, {{ $store.auth.user?.email }}!</p>
        <div class="nested">
          <!-- Nested <router-view> for children -->
          <router-view />
        </div>
      </div>
    </template>
    
    <script setup>
    // Per-component route guard example
    import { onBeforeRouteEnter, onBeforeRouteLeave } from 'vue-router'
    import { useAuthStore } from '../stores/auth.js'
    
    const authStore = useAuthStore()
    
    onBeforeRouteEnter((to, from, next) => {
      if (!authStore.isAuthenticated) {
        next(false) // Abort navigation
      } else {
        next()
      }
    })
    
    onBeforeRouteLeave((to, from, next) => {
      if (confirm('Are you sure you want to leave?')) {
        next()
      } else {
        next(false)
      }
    })
    </script>
    
    <style scoped>
    .nested { border: 1px solid #ccc; padding: 20px; margin-top: 20px; }
    </style>
    
    <!-- views/Profile.vue -->
    <template>
      <div>
        <h2>Profile {{ $route.params.id ? `ID: ${$route.params.id}` : 'Home' }}</h2>
        <p v-if="$route.query.tab === 'edit'">Edit mode</p>
      </div>
    </template>
    
    <script setup>
    // Props from route
    defineProps({
      id: String
    })
    </script>
    
    <!-- views/Settings.vue -->
    <template>
      <div>
        <h2>Settings (Admin Only)</h2>
        <p>Configure your app settings here.</p>
      </div>
    </template>
    
    <!-- views/Admin.vue -->
    <template>
      <div>
        <h1>Admin Panel</h1>
        <p>Super secret admin stuff.</p>
      </div>
    </template>
    
    <!-- views/NotFound.vue -->
    <template>
      <div>
        <h1>404 - Page Not Found</h1>
        <router-link to="/dashboard">Go Home</router-link>
      </div>
    </template>
    
    // stores/auth.js (Pinia store for auth state)
    import { defineStore } from 'pinia'
    import { ref } from 'vue'
    
    export const useAuthStore = defineStore('auth', () => {
      const user = ref(null)
      const isAuthenticated = ref(false)
      const isAdmin = ref(false)
    
      const login = async (credentials) => {
        // Simulate API
        user.value = credentials
        isAuthenticated.value = true
        isAdmin.value = credentials.isAdmin || false
        localStorage.setItem('auth', JSON.stringify({ user: credentials.email, isAdmin: isAdmin.value }))
      }
    
      const logout = () => {
        user.value = null
        isAuthenticated.value = false
        isAdmin.value = false
        localStorage.removeItem('auth')
      }
    
      const checkAuth = async () => {
        const stored = localStorage.getItem('auth')
        if (stored) {
          const { user: email, isAdmin: admin } = JSON.parse(stored)
          user.value = { email }
          isAuthenticated.value = true
          isAdmin.value = admin
        }
      }
    
      return { user, isAuthenticated, isAdmin, login, logout, checkAuth }
    })
    
    // main.js
    import { createApp } from 'vue'
    import { createPinia } from 'pinia'
    import App from './App.vue'
    import router from './router'
    
    const app = createApp(App)
    app.use(createPinia())
    app.use(router)
    app.mount('#app')
    

    Setup Instructions

    1. Create a new Vue 3 app: npm init vue@latest my-app (choose Vue Router & Pinia).
    2. Install dependencies: npm install vue-router@4 pinia.
    3. Replace files with the code above.
    4. Run npm run dev.

    Key Features Demonstrated

    • Nested Views: <router-view> in Dashboard.vue for /dashboard/*.
    • Dynamic Segments: /dashboard/profile/:id.
    • Query Params: Preserved in redirects.
    • Guards:
      • Global: beforeEach for auth/guest/admin checks.
      • Per-Route: meta fields.
      • Per-Component: onBeforeRouteEnter/Leave.
    • Redirects & Named Routes: Clean navigation.
    • Auth State: Pinia + localStorage for persistence.
    • 404 Handling: Catch-all route.

    Test:

    • Login as user@example.com / password → Dashboard.
    • Login as admin@example.com / admin → Settings.
    • Try accessing /admin without admin → Redirected.
    • Guards prevent unauth access and show nested views correctly.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.