はじめに
vue3でDatePicekerをいろいろと調べてみた。
でも、どれもコンポーネント内で非同期で選択できない日を設定することができなかった。
例:予約アプリで、apiに予約済みの日付を問い合わせて表示する
そこでvueのSuspenseを使い対応してみた。
今回はelement plusを使ったが他のDatePickerでも大丈夫だと思います。
コード
App.vue
<template>
<Suspense>
<template #default>
<DatePickerComponent></DatePickerComponent>
</template>
<template #fallback>
<span>読み込み中…</span>
</template>
</Suspense>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import DatePickerComponent from './components/DatePickerComponent.vue';
export default defineComponent({
name: 'App',
components: {
DatePickerComponent
}
});
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
DatePickerComponent.vue
<script lang="ts" setup>
import { ref } from 'vue'
const select = ref('')
let list:Date[] = []
const disabledDate = (time: Date) => {
let result = list.find(v => v.getTime() == time.getTime())
if(result){
return true;
}
return false
}
const sleep = async () => {
return new Promise(resolve => {
setTimeout(() => {
resolve(1)
}, 3000)
})
}
await sleep();
/*ここから先はapiからデータが取れて前提。今回は明日が選択不可にしています*/
const date = new Date();
let tomorrow = new Date(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0,0);
tomorrow.setDate(tomorrow.getDate() + 1)
list.push(tomorrow)
</script>
<template>
<el-date-picker
v-model="select"
type="date"
placeholder="Pick a day"
:disabled-date="disabledDate"
/>
</template>
まとめ
本当はdisabledDataの中で非同期で扱いたい。
例えば、来月に移動したときに、いつdisbaledにするかapiに聞きたいから。
#参考
git
https://github.com/kawamurashin/vue3-suspense-el-test1