Vue.js でルート遷移時にデータを更新する方法

1. プロジェクト内のルート遷移

mountedcreated は一度だけ実行されるため、データの変更を監視しても効果がありません。プロジェクトで <keep-alive> を使用している場合、activated フックを使用してデータの更新を監視します。

1.1. パラメータを変更するページ (home.vue)

各遷移時にパラメータを変更し、異なるタイムスタンプを取得することで、URL を次のように設定します: http://localhost:8080/#/noticeDetail?time=1641284450820

1.2. キャッシュしないルート設定

{
    path: "/noticeDetail",
    name: "noticeDetail",
    component: pages.noticeDetail,
    meta: {
        title: "お知らせ情報",
        code: "noticeDetail",
        noCache: false
    }
},

1.3. 目的のページ (noticeDetail.vue) での監視実装

activated() { // <keep-alive> を使用しているので、activate フックを使用してデータを再読み込み
    this.init(); // ページの初期化
}

2. 同じルートへの遷移時の問題解決

this.$router.push() を使用して同じルートに遷移すると、エラーが発生し、ページのデータも更新されません。

2.1. ナビゲーションエラーの解決

ルートが重複しているために発生する NavigationDuplicated エラーを解決します。

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err);
}

2.2. ルートデータの再読み込み

現在のルートが重複している場合は、削除して再読み込みします。

const time = Date.now();
sessionStorage.setItem('noticeDetail', JSON.stringify(params));
if (this.$route.name === "noticeDetail") {
    this.store.delView(this.$route); // store は inject で注入されている
    this.$router.push({ path: '/noticeDetail', query: { time } });
    setTimeout(() => {
        location.reload();
    }, 0);
} else {
    this.$router.push({ path: '/noticeDetail', query: { time } });
}

2.3. 改善策: ルート変更の監視

異なるプロジェクト間でもルートの変更を監視し、API を再呼び出してページのデータを更新します。

watch: {
    $route(to) {
        if (this.$route.name === 'noticeDetail') {
            this.init(); // 後続のビジネスロジック処理
        }
    }
}

タグ: vue.js Vue Router keep-alive activated watch

5月20日 11:53 投稿