0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nuxt3のルーティングについて

Posted at

はじめに

Nuxt3で開発する際に、ページのルーティングについて下記のように戸惑うことがあります。
たとえば、「app.vueには何を書いたらいいの??」。
Next.jsのように自由に書いているとルーティングに失敗してしまいます。
この記事では、私を含めてルーティングについての備忘録を残しておきます。

ディレクトリ構成

Nuxt3では、ルーティングする際はcomponentspagesフォルダを別に作成してその配下にVueファイルを配置するようにします。

ちなみにapp.vueは、プロジェクト作成時の時と同じ階層になります。

.
└── Project/
    ├── .nuxt
    ├── .output
    ├── components/
    │   └── navbar/
    │       └── navbar.vue
    ├── node_modules
    ├── pages/
    │   ├── adminUsers
    │   ├── generalUsers/
    │   │   └── registration/
    │   │       └── registration.vue
    │   ├── index.vue
    │   ├── public/
    │   │   ├── favicon.ico
    │   │   └── robots.txt
    │   └── server/
    │       └── tsconfig.json
    ├── app.vue
    ├── nuxtconfig.ts/
    │   ├── package.json
    │   └── package-lock.json
    ├── README
    └── tsconfig.json

pagesフォルダにアクセスするにはapp.vueは記載する内容

前述したpagesフォルダにトップページapp.vueからアクセスするには、<NuxtPage />コンポーネントが必要になります。

app.vue
<template>
  <div>
    <NuxtPage />
  </div>
</template>

index.vueを作成して共通コンポーネントを読み込む

index.vueを作成して共通のコンポーネントを作成します。このindex.vueがあることでプロジェクトを起動して最初のページが表示された時にレイアウトが表示されるようになります。

pages/index.vue
<script setup="ts">
import { Navbar } from "#components";
</script>

<template>
    <Navbar/>
    <div>
        
    </div>
</template>

Navbarコンポーネントは、componentsディレクトリで作成後に、index.vueにインポートしています。
べつの話になりますが、ページ遷移するときに使用するモジュールuseRouterは、管理パッケージでインポートしなくても使えます。

この点は、Next.jsとは異なる点です。

components/navbar/nabvar.vue
<script setup="ts">
const router = useRouter();
const clickRegistration = ()=>{
    router.push('/generalUsers/registration/registration');
}
</script>
<template>
    <v-card>
        <v-layout>
            <v-app-bar color="primary">
                <v-app-bar-nav-icon variant="text" @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
                <v-toolbar-title>My Todo Task</v-toolbar-title>
                <template v-if="$vuetify.display.mdAndUp">
                    <v-btn icon="mdi-magnify" variant="text"></v-btn>
                    <v-btn icon="mdi-filter" variant="text"></v-btn>
                </template>
                <v-btn @click="clickRegistration">Register</v-btn>
            </v-app-bar>
        </v-layout>
    </v-card>
</template>

ルーティングの確認

では、app.vue<NuxtPage />コンポーネントを追加したことでページ遷移できるか確認してみましょう。
ナビゲーションバーの、「Regiter」ボタンをクリックすると...

image.png

ちゃんと登録ページに遷移できましたね。
image.png

以上です。

参考サイト

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?