File: meta.md

package info (click to toggle)
vue-router.js 3.6.5~ds1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,560 kB
  • sloc: javascript: 8,524; sh: 22; makefile: 5
file content (53 lines) | stat: -rw-r--r-- 2,187 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# ルートメタフィールド

<div class="vueschool"><a href="https://vueschool.io/courses/vue-router-for-everyone?friend=vuerouter" target="_blank" rel="sponsored noopener" title="Learn how to build powerful Single Page Applications with the Vue Router on Vue School">Watch a free video course about Vue Router on Vue School</a></div>

ルートの定義をする際に `meta` フィールドを含めることができます。

```js
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // メタフィールド
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})
```

ではどのように `meta` フィールドにアクセスしましょう?

まず、 `routes` 設定の中の各ルートオブジェクトは**ルートレコード**と呼ばれます。ルートレコードはネストされているかもしれません。したがって、ルートがマッチした時に、潜在的には 1 つ以上のルートレコードがマッチされる可能性があります。

例えば上記のルート設定で、 `/foo/bar` という URL は親のルートレコードにも子のルートレコードにもマッチします。

ルートにマッチした全てのルートレコードは `$route.matched` 配列として `$route` オブジェクト上で (また、ナビゲーションガード上のルートオブジェクトでも) アクセス可能になります。

メタフィールドをグローバルナビゲーションガードで確認するユースケースの例:

```js
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // このルートはログインされているかどうか認証が必要です。
    // もしされていないならば、ログインページにリダイレクトします。
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // next() を常に呼び出すようにしてください!
  }
})
```