Vue-Router まとめ

● Vue-Router まとめ

ルーターの設定を記述するファイル router/index.ts

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/profile",
      name: "profile",
      component: ProfileView,
    },
    // リダイレクトさせる場合
    {
      path: "/",
      redirect: "/mypage",
    },
    // 特定のパラメーター (例:isGuest) を渡す 場合
    {
      path: "/login",
      name: "Login",
      component: LoginView,
      meta: { isGuest: true },
    },
  ],
});

const aughGuard = () => {
  if (認証チェック){
    next();
    return;
  }

  next({ path: "/login" });
}

// ルーティング前に認証チェックを実行
router.beforeEach((to, from, next) => {
  authGuard(to, next);
});

● 画面遷移の方法(コンポーネント内のテンプレートからリンクをする)

<template>
    <router-link to="/about">Go to About</router-link>
</template>

● 画面遷移の方法(templateに直接記述)

<button class="btn" @click="$router.push('/login')">戻る</button>

● 画面遷移の方法(メソッドを使用)

nameで指定する場合

import { useRouter } from "vue-router";

const router = useRouter();

await router.push({ name: "Login" });

pathで指定する場合

import { useRouter } from "vue-router";

const router = useRouter();

await router.push("/login");

● Vue-Router で画面遷移した時に、親画面を消さずに、子画面の一部のみを入れ替える

/ の下に /child1 /child2 を子画面として追加する

src/router/index.ts

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: HomeView,
      children: [
        {
          path: "/child1",
          components: {
            default: Child1View,
          },
        },
        {
          path: "/child2",
          components: {
            default: Child2View,
          },
        },
      ],
    }
  ],
});

親の src/views/HomeView.vue に 子画面用の router-view を追加します

src/views/HomeView.vue

<template>
  <div class="container">
    <h1>Home</h1>
    <router-view></router-view>
  </div>
</template>

これで、 /child1 , /child2 を表示しているときは HomeView.vueはアンマウントされません。

● this.$router , this.$route にアクセスする

引用: https://qiita.com/azukiazusa/items/9f467fdea7298baf3476

useRouter()・useRoute()に置き換える
ルーターオブジェクトを得るためには、vue-rouerからuseRouterまたはuseRoute関数をインポートします。それぞれの関数は以下のように対応しています。
Options API Composition API
this.$router useRouter
this.$route useRoute

● ページがリロードされたかどうかを検知する

src/router/index.ts

router.beforeEach((to, from, next) => {
  // from.name が取得できる時はパスを保存。できないときは "" を保存
  sessionStorage.setItem("referrer", from.name ? from.path : "");
  authenticate(to, next);
});

各コンポーネント

function isPageReload() {
  return sessionStorage.getItem("referrer") === "";
}

if isPageReload(){
    alert("reloadです");
}

とすれば検知できます。

● htmlヘッダのタイトルを vue-router で設定した値で変更する

https://github.com/vinicius73/vue-page-title#vue-router-integration

● 画面遷移したときのスクロール位置を設定する

https://router.vuejs.org/guide/advanced/scroll-behavior.html

No.2176
02/10 11:06

edit