Trung BìnhVue.js iconVue.js

Route meta và type-safe route meta trong Vue Router 4?

Route meta cho phép đính kèm custom data vào routes — thường dùng cho auth, breadcrumbs, page titles:

typescript
// router/index.ts — declare meta type
import 'vue-router'

declare module 'vue-router' {
  interface RouteMeta {
    requiresAuth?: boolean
    roles?: string[]
    title?: string
    breadcrumb?: string
  }
}

const routes = [
  {
    path: '/admin',
    component: AdminLayout,
    meta: { requiresAuth: true, roles: ['admin'], title: 'Admin Panel' },
    children: [
      {
        path: 'users',
        component: UsersView,
        meta: { breadcrumb: 'Users Management' },
      }
    ]
  },
]

// Global guard dùng meta
router.beforeEach((to) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    return { name: 'Login', query: { redirect: to.fullPath } }
  }
})

// Component access
const route = useRoute()
console.log(route.meta.title)  // Type-safe nhờ declaration merging

Pitfall: to.meta tổng hợp metadata từ tất cả matched routes (parent + child) — child ghi đè parent.

Xem toàn bộ Vue.js cùng filter theo level & chủ đề con.

Mở danh sách Vue.js