ลองสร้าง vue component เป็น One-way Binding Component ที่ทำหน้าที่ง่าย ๆ ในการรับ datetime แล้วแสดงออกมาเป็น locale ( รูปแบบท้องถิ่น ) สำหรับใช้ใน laravel ดู
resources/js/Components/DateLocale.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | < script lang = "ts" > interface Window { locales: string[]; datetimeOptions: { year: 'numeric' | '2-digit'; month: 'numeric' | '2-digit'; day: 'numeric' | '2-digit'; hour: 'numeric' | '2-digit'; minute: 'numeric' | '2-digit'; }; } export default { computed: { formattedDate(this: { datetime: string }) { const date: Date = new Date(this.datetime); if (!window.datetimeOptions) { console.warn('window.datetimeOptions is undefined, using default options'); window.datetimeOptions = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' }; } const datetimeOptions = { ...window.datetimeOptions, year: window.datetimeOptions.year as 'numeric' | '2-digit', month: window.datetimeOptions.month as 'numeric' | '2-digit', day: window.datetimeOptions.day as 'numeric' | '2-digit', hour: window.datetimeOptions.hour as 'numeric' | '2-digit', minute: window.datetimeOptions.minute as 'numeric' | '2-digit' }; const userLocales = window.userLocales ? [...window.userLocales] : ['en-US']; return date.toLocaleDateString(userLocales, datetimeOptions); } }, name: 'DateLocale', props: { datetime: { type: String, required: true } } } </ script > < template > < div >{{ formattedDate }}</ div > </ template > |
บรรทัดที่ 40 คือ ชื่อ
บรรทัดที่ 41 คือ ตัว attribute ที่จะรับ datetime เข้ามา
ประกาศตัวแปรใน resources/js/app.ts
1 2 3 4 5 6 7 8 9 10 11 12 | //config variables const datetimeOptions = { day: 'numeric' , hour: 'numeric' , minute: 'numeric' , month: 'short' , year: 'numeric' }; window.datetimeOptions = datetimeOptions; const locales = (navigator.languages && navigator.languages.length) ? navigator.languages : navigator.language || 'en' ; window.locales = locales; |
เป็น format รูปแบบการแสดงผล และภาษาที่ user ใช้อยู่
อย่าลืม register component ใน app.ts หรือ vue.ts เช่นapp.component('date-locale', DateLocale)
ใน view เช่น resources/views/tickets/show.blade.php ใช้โดย<date-local
e
datetime="{{ $ticket->created_at }}" />
อ่านเพิ่มเติม