LoginSignup
6
5

More than 3 years have passed since last update.

Nuxt.jsの動的ルーティングでQiitaっぽい構成を作ってみるメモ

Last updated at Posted at 2020-09-02

Qiitaと同様の構成を作ってみたメモです。

通常のNuxt.jsの動的ルーティング

こんな構成にすると

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

https://ドメイン/users/<ユーザー名> みたいな構成を作ることが出来ます。

https://ja.nuxtjs.org/guide/routing#%E5%8B%95%E7%9A%84%E3%81%AA%E3%83%AB%E3%83%BC%E3%83%86%E3%82%A3%E3%83%B3%E3%82%B0

このユーザー名の部分がURLにアクセスした際の値で動的に変わります。

Qiitaっぽい構成って?

(2020年9月時点)Qiitaの記事は以下のような構成です。

https://ドメイン/<ユーザー名>/items/<記事ID>

例: https://qiita.com/n0bisuke/items/ceaa09ef8898bee8369d

先ほどのユーザー名だけが動的な場合と違って、ネストされて記事IDも動的になっています。

これをNuxtで再現したいなという話です。

こんなディレクトリ構成

参考記事などを見ながら触ってたらこんな構成でうまく行きました。

pages/
--| _userid/
-----| items
--------| _itemid.vue
-----| index.vue
--| index.vue

末端となる記事ページは/pages/_userid/items/_itemid.vueになります。

スクリーンショット 2020-09-02 9.42.33.png

出来てみるとそんなもんかという感じですね。

記事ページのコード

メモ程度です。

_itemid.vue
<template>
  <section class="section">
    {{userid}}のitem:{{itemid}}
  </section>
</template>

<script>

export default {
  name: 'item',

  data(){
    return{}
  },

  computed: {},
  mounted(){},
  methods: {},

  async asyncData({ $content, params }) {
    const userid = params.userid;
    const itemid = params.itemid;
    return {userid, itemid};
  },
}
</script>

参考

https://qiita.com/notsunohito/items/46bc9c6ad88fed46ea14

6
5
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
6
5