LoginSignup
2
0

More than 1 year has passed since last update.

【Nuxt.js】自動ルーティング設定

Last updated at Posted at 2021-05-04

はじめに

nuxt では vue-router を自分で設定する必要がないです!
pages ディレクトリ配下に作った vueファイルに対して、自動的にルーティングが行えるように色々やってくれるようなので、ドキュメント見ながら簡単にまとめたいと思います。

自動的にルーティングを生成

下記のような .vue ファイルを pages/ 配下に作成すると、、

pages/
--| product/
-----| index.vue
-----| name.vue
--| index.vue

自動的に以下が生成されます

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

ここで定義されているルートは、こんな意味です。

{
    name: 'product',
    path: '/product',   //このパスにアクセスしたら
    component: 'pages/product/index.vue'   //このコンポーネントを呼ぶ
}

動的な場合

Qiitaなどの記事を API から取得する場合、記事の名前や記事IDのようなものがURIに入ることになります。そうなると、ルートの名前を決定することができないので、動的に設定する必要があります。

その場合は、アンダーバーをファイル名の頭に付けます。

pages/
--| article/
-----| _articleid.vue

下記が生成されます

{
    name: 'articleid',
    path: '/article/:articleid',
    component: 'pages/article/_articleid.vue'
}

これにより、https://itblog.com/article/943095435 このようなURIで記事にアクセスできます。

記事IDを取得する

動的な記事ページ article/_articleid.vue があるとします。この articleid にアクセスするには、 this.$route.params.articleid でいけるみたいです。

URIを指定してページ遷移するには

NuxtLink コンポーネントを使ってください。

<template>
  <NuxtLink to="/article">記事一覧</NuxtLink>
</template>

さいごに

vue はポートフォリオつくる際に触りましたが、nuxt は初。何が便利なんだろうってところから一つ一つ理解。

Nuxt に用意された router プロパティで色々カスタマイズできるみたいです。

参考文献

2
0
0

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
2
0