はじめに
Vuetifyは手軽にリッチなUIを作成することができますが、現時点でVuetify3のバージョンのv-date-pickerに関する公式ドキュメントは少ないです。
この記事では、v-date-pickerという非常に使いやすい日付選択コンポーネントを利用し、v-date-pickerのキャンセルボタンをクリックした際にダイアログを非表示にする方法を説明します。
前提条件
■Vuetify3をプロジェクトで導入していること
https://github.com/vuetifyjs
■Vue3のCompositionAPIを用いて開発していること
実装手順
結論
結論から申しますと以下のコードになります。
<template>
<v-card-title class="d-flex align-center justify-center" style="font-size: 16px" color="grey-darken-2">
日付
</v-card-title>
<v-card-subtitle class="d-flex align-center justify-center">
<v-text-field
@click="handleClick"
label="日付を選択"
outlined
readonly
></v-text-field>
</v-card-subtitle>
<v-row justify="center">
<v-dialog
v-if="menu"
v-model="menu"
:close-on-content-click="false"
full-screen
>
<v-card class="d-flex justify-center align-center">
<v-date-picker
@click:cancel="handleCancel"
></v-date-picker>
</v-card>
</v-dialog>
</v-row>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { VDatePicker } from 'vuetify/labs/VDatePicker';
let menu = ref<boolean>(false);
const handleClick = () => {
menu.value = true;
};
const handleCancel = () => {
menu.value = false;
};
</script>
初期設定
まず、以下のようにテキストフィールドとv-date-pickerとそれを囲むv-dialogを配置します。
<template>
<v-card-title class="d-flex align-center justify-center" style="font-size: 16px" color="grey-darken-2">
日付
</v-card-title>
<v-card-subtitle class="d-flex align-center justify-center">
<v-text-field
@click="handleClick"
label="日付を選択"
outlined
readonly
></v-text-field>
</v-card-subtitle>
<v-row justify="center">
<v-dialog
v-if="menu"
v-model="menu"
:close-on-content-click="false"
full-screen
>
<v-card class="d-flex justify-center align-center">
<v-date-picker
></v-date-picker>
</v-card>
</v-dialog>
</v-row>
</template>
キャンセルボタンのイベントをリスニング
v-date-pickerにはデフォルトでキャンセルボタンと保存ボタンがあります。
キャンセルボタンがクリックされた時にイベントをキャッチするには、@click:cancelを使用します。
@click:cancelはVue.jsのデベロッパーツールを確認すると、VDatePickerに標準で搭載されていることが確認できます。
<v-date-picker
@click:cancel="handleCancel"
></v-date-picker>
イベントハンドラの作成
次に、handleCancel 関数を作成して、menu の値を false に設定します。これにより、ダイアログが閉じられます。
const handleCancel = () => {
menu.value = false;
};
以上で、キャンセルボタンをクリックした際にダイアログが閉じるようになります。
まとめ
Vuetifyのv-date-pickerの挙動をカスタマイズする際のドキュメントは少ないため、開発者ツールやOSSなどを確認する必要があるかと思いますが、この記事が皆さんの開発に役立てば幸いです。