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

Vue3 の Composition API で、Vue Router を効率的に利用し、ナビゲーションの制御、ページ遷移、パラメータの受け渡しを実装します。

1. 準備

まずは、プロジェクトに Vue Router をインストールします。

npm install vue-router

次に、main.ts ファイルで Vue Router を初期化します。

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

createApp(App).use(router).mount('#app');

2. ルーティング設定

router/index.ts ファイルで、ルーティング設定を行います。

import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import AboutView from '../views/AboutView.vue';

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView,
  },
  {
    path: '/products/:id',
    name: 'product',
    component: ProductView,
    props: true, 
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

export default router;

この例では、HomeViewAboutViewProductView といったコンポーネントを定義し、それぞれに対応するパスを設定しています。

ProductView は、products/:id のようにパラメータを含んだパスを使用しており、props: true を設定することで、パラメータをコンポーネントに渡すことができます。

3. setup 関数での Router の利用

コンポーネントの setup 関数内で、useRouter を使用して Router インスタンスを取得します。

<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();

</script>

4. ナビゲーションの制御

router.push() メソッドを使って、別のページへ遷移できます。

<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();

const onNext = () => {
  router.push('/about');
};
</script>

<template>
  <button @click="onNext">次のページへ</button>
</template>

router.replace() メソッドを使うと、現在の履歴を置き換えて遷移できます。

5. パラメータの受け渡し

ProductView のような、パラメータを持つページでは、$route.params でパラメータにアクセスできます。

<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();

</script>

<template>
  <div>
    <h1>商品詳細 - {{ $route.params.id }}</h1>
    <!-- 商品情報など -->
  </div>
</template>

router.push() でパラメータを渡す場合、オブジェクトで指定します。

router.push({
  name: 'product',
  params: { id: 123 },
});

6. まとめ

Composition API を使用することで、Vue Router との連携がよりシンプルになり、コードの可読性も向上しました。

  • useRouter を使用して Router インスタンスを取得
  • router.push()router.replace() でページ遷移を制御
  • $route.params でパラメータにアクセス
    今回は基礎的な使い方についてまとめましたが、他にも使い方がありそうなので今後記事にまとめたいと思います。
5
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
5
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?