0
0

More than 1 year has passed since last update.

【学習記録⑱】$routerを用いてページ遷移を行う!

Posted at

はじめに

Vue.jsを最近勉強し始めたので学んだ文法などを備忘録としてメモしていこうと思います。
前々回の記事にて、router-linkを用いてページ遷移する方法について記載しましたが、今回は$routerを用いてページ遷移を行う方法について記載します。

なお、以下の公式ドキュメントによるとrouter-linkの動作の中身が$routerとのことなので、両者での挙動の違い等はないようです。

サンプルコード

上記のドキュメントを参考に、$routerを用いてページ遷移を行ってみます。
今回は「朝食ボタン」「詳細ボタン」をクリックすると、それぞれのページに遷移するという内容にします。

App.vue
<template>
  <button @click="toBreakfast">朝食ボタン</button>
  <button @click="toDetails">詳細ボタン</button>
  <router-view></router-view>
</template>

<script>
export default {
  methods: {
    toBreakfast() {
      this.$router.push({ path: "/Morning/breakfast"});
    },
    toDetails() {
      this.$router.push({ path: "/Morning/details" });
    },
  },
};
</script>
router.js
import Morning from './views/Morning.vue';
import MorningDetails from './views/MorningDetails.vue';
import MorningBreakfast from './views/MorningBreakfast.vue';
import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/Morning',
            component: Morning,
            children: [
                {
                    path: 'details',
                    component: MorningDetails
                },
                {
                    path: 'breakfast',
                    component: MorningBreakfast
                }
            ]
        },
    ]
});

export default router;
Morning.vue
<template>
  <div>おはよう</div>
  <router-view></router-view>
</template>
MorningBreakfast.vue
<template>
  <div>朝ごはんはパンです。</div>
</template>
MorningDetails.vue
<template>
  <div>だんだん冷えてきたので体調には気を付けていきましょう。</div>
</template>

結果

それぞれのボタンをクリックすると対象のページへ遷移することが確認できます。

朝食ボタンクリック
pic.png
詳細ボタンクリック
pic1.png

おわりに

今回はpathオプションを用いて遷移先の指定等を行いましたが、調べてみるとnameオプションなどを利用して遷移先を指定することもできるようなので次回はそちらの方法について調査して記事にしていきたいと思います。

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