LoginSignup
36
20

More than 5 years have passed since last update.

Nuxt.js ルーティングの設定方法

Last updated at Posted at 2019-05-13

初めてNuxt.jsを触り、どこにルーティングが書かれているのかがわからなかったのでメモ

nuxtはvue routerを利用してルーティングを作成している。

ほぼ公式サイトのルーティングの記述通りなのでそちらがよければそちらを

ルーティングの決め方

公式サイトより、

Nuxt.js は pages ディレクトリ内の Vue ファイルの木構造に沿って、自動的に vue-router の設定を生成します

と書かれている。なのでRailsにおけるroutes.rbは存在しない

静的ルーティング

ではpagesのディレクトリ構成を元にどういったルーティングが構成されているのかを見てみる。

pages/
--| user/
-----| index.vue
-----| one.vue
--| index.vue

の場合、

router: {
  routes: [
    {
      name: 'index',
      path: '/',
      component: 'pages/index.vue'
    },
    {
      name: 'user',
      path: '/user',
      component: 'pages/user/index.vue'
    },
    {
      name: 'user-one',
      path: '/user/one',
      component: 'pages/user/one.vue'
    }
  ]
}

rootはpages直下のindex.vue, それ以外のルーティングはディレクトリとファイル名に応じてルーティングが作成される。

ちなみにnameはrouter-linkなどでリンクを作るときにnameで指定したりできるもの

動的ルーティング

/users/34/

のようにid名などで動的にリンクを作成する場合ファイル名、ディレクトリ名にアンダースコアをつけることで可能になる。

pages/
--| users/
-----| _id.vue

の場合、

router: {
  routes: [
    {
      name: 'users-id',
      path: '/users/:id?',
      component: 'pages/users/_id.vue'
    }
  ]
}

となる。

まとめ

pagesのディレクトリ構成をみることでrouteがわかる。

ということはわかったのだが、一覧でみる方法はないのか、、、

追記

下記コメントでkeita06さんからrouting一覧は.nuxt/router.jsでみることが可能とのコメントをいただいた

そちらで確認することが可能

 {
      path: "/",
      component: _e707290e,
      name: "index"
    }],

ただし、buildする影響からかcomponentが定数化されている。
ファイル上部に宣言されているのでそこを確認するとわかる

参考文献

公式サイト

36
20
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
20