Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 23 additions & 37 deletions docs/guide/advanced/meta.md
Original file line number Diff line number Diff line change
@@ -1,51 +1,37 @@
# Route Meta Fields

Sometimes, you might want to attach arbitrary information to routes like transition names, who can access the route, etc. This can be achieved through the `meta` property which accepts an object of properties and can be accessed on the route location and navigation guards. You can define `meta` properties like this:
Route Meta Fields allow you to attach **arbitrary data** to route records. This is invaluable for storing route-specific information that needs to be accessed during navigation or within components, such as authorization requirements, transition names, or page titles.

This is achieved through the **`meta`** property, which accepts an object of custom properties.

## Defining Meta Fields

The `meta` field is defined directly on a route record. The values are merged across nested routes, meaning a child route can access the `meta` properties of its parent.

```js
import VueRouter from 'vue-router'

const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
path: '/admin',
component: AdminLayout,
// Parent route meta: authentication required for all children
meta: { requiresAuth: true },
children: [
{
path: 'bar',
component: Bar,
// a meta field
meta: { requiresAuth: true }
path: 'users',
component: AdminUsers,
// Child route meta: includes a specific title
meta: { isAdmin: true, title: 'Manage Users' }
},
{
path: 'login',
component: Login,
// Explicitly overriding the parent meta to allow public access
meta: { requiresAuth: false }
}
]
}
]
})
```

So how do we access this `meta` field?

First, each route object in the `routes` configuration is called a **route record**. Route records may be nested. Therefore when a route is matched, it can potentially match more than one route record.

For example, with the above route config, the URL `/foo/bar` will match both the parent route record and the child route record.

All route records matched by a route are exposed on the `$route` object (and also route objects in navigation guards) as the `$route.matched` Array. Therefore, we will need to iterate over `$route.matched` to check for meta fields in route records.

An example use case is checking for a meta field in the global navigation guard:

```js
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // make sure to always call next()!
}
})
```