useConfirmDialog

useConfirmDialog

モーダルと確認ダイアログチェーンをサポートするイベントフックを作成します。

関数はテンプレートで使用でき、フックはモーダルダイアログやユーザーの確認を必要とする他のアクションのビジネスロジックの便利な骨組みです。

関数とフック

  • reveal() - onReveal フックをトリガーし、revealed.valuetrue に設定します。confirm() または cancel() によって解決されるプロミスを返します。
  • confirm() - isRevealed.valuefalse に設定し、onConfirm フックをトリガーします。
  • cancel() - isRevealed.valuefalse に設定し、onCancel フックをトリガーします。

基本的な使い方

フックを使用する

<script setup lang="ts">
import { useConfirmDialog } from '@vueuse/core'

const { isRevealed, reveal, confirm, cancel, onReveal, onConfirm, onCancel }
  = useConfirmDialog()
</script>

<template>
  <button @click="reveal">
    モーダルを表示
  </button>

  <teleport to="body">
    <div v-if="isRevealed" class="modal-bg">
      <div class="modal">
        <h2>確認しますか?</h2>
        <button @click="confirm">
          はい
        </button>
        <button @click="cancel">
          キャンセル
        </button>
      </div>
    </div>
  </teleport>
</template>

プロミス

プロミスを使う方が好みの場合:

<script setup lang="ts">
import { useConfirmDialog } from '@vueuse/core'

const {
  isRevealed,
  reveal,
  confirm,
  cancel,
} = useConfirmDialog()

async function openDialog() {
  const { data, isCanceled } = await reveal()
  if (!isCanceled)
    console.log(data)
}
</script>

<template>
  <button @click="openDialog">
    モーダルを表示
  </button>

  <teleport to="body">
    <div v-if="isRevealed" class="modal-layout">
      <div class="modal">
        <h2>確認しますか?</h2>
        <button @click="confirm(true)">
          はい
        </button>
        <button @click="confirm(false)">
          いいえ
        </button>
      </div>
    </div>
  </teleport>
</template>