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?

Vue3 + VueRouter で離脱防止ポップアップ作成

Last updated at Posted at 2025-03-20

image.png

編集フォームなどから離脱する際に出てくるこの画面

前提

  • vue: v3.5.13
  • vue-router: 4.5.0
  • Composition API

ポイント

・ブラウザでの制御箇所(戻る・リロードなど)とVueRouterでの制御箇所、それぞれで作ってあげる必要があります。

VueRouter部分

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

onBeforeRouteLeave((to, from) => {
  if (to.name != "next"){
    const answer = window.confirm(
    "入力内容は破棄されますが、よろしいですか?"
    )
    if (!answer) return false
  }
})

onBeforeRouteLeave()を使用することで、現在のページから離れる前段階で処理を呼び出すことができます。今回は確認用のポップアップを呼び出します。

toからは遷移先の、fromからは遷移元のルートオブジェクトが使用できます。今回は遷移先のオブジェクトに対してアクセスし、入力後の画面かを確認しています。

冒頭でも述べましたが、戻るボタンやリロード等、ブラウザ側の操作で画面から離れる場合にはonBeforeRouteLeave()が動作しません。こちらは別途作成しましょう。

onBeforeRouteLeave()に関しての詳細

ブラウザ部分

<script setup>
const confirm = (e) => {
        e.preventDefault()
        e.returnValue ="入力内容は破棄されますが、よろしいですか?"
}

window.addEventListener("beforeunload", confirm)
</script>

こちらは生のJSで書いてあげる必要があります。

ほとんどのブラウザではreturnValueに設定した値ではなく、ブラウザ固有のメッセージが表示されます。

ブラウザによっては画面に対して操作が行われていない場合、戻るボタン等を押してもbeforeunloadが呼ばれません。フォームなどに値を入力した状態でお試しください。

beforeunloadについてはこちら

コード

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

const confirm = (e) => {
        e.preventDefault()
        e.returnValue =" confirmText"
}

window.addEventListener("beforeunload", confirmBrowserRouter)





onBeforeRouteLeave((to, from) => {
  if (to.name != "next"){
    const answer = window.confirm(
    "入力内容は破棄されますが、よろしいですか?"
    )
    if (!answer) return false
  }
})
</script>
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?