Home > Article > Web Front-end > How to use Vue to implement calendar selection effects
How to use Vue to implement calendar selection effects
In modern web application development, calendar selection is a common functional requirement. Through calendar selection, users can easily select dates to query events or make appointments. In this article, we will introduce how to use the Vue framework to implement a simple and practical calendar selection effect to meet the needs of daily development.
npm install vue vue-router vuex
<template> <div class="calendar"> <h2>{{ year }}年{{ month }}月</h2> <table> <thead> <tr> <th v-for="week in weeks" :key="week">{{ week }}</th> </tr> </thead> <tbody> <tr v-for="week in calendar" :key="week"> <td v-for="day in week" :key="day" @click="selectDate(day)">{{ day }}</td> </tr> </tbody> </table> </div> </template> <script> export default { data() { return { now: new Date(), year: 0, month: 0, weeks: ['日', '一', '二', '三', '四', '五', '六'], calendar: [] }; }, mounted() { this.updateCalendar(); }, methods: { updateCalendar() { const firstDay = new Date(this.now.getFullYear(), this.now.getMonth(), 1); const lastDay = new Date(this.now.getFullYear(), this.now.getMonth() + 1, 0); this.year = this.now.getFullYear(); this.month = this.now.getMonth() + 1; const gap = firstDay.getDay(); const days = lastDay.getDate(); let calendar = []; let week = []; for (let i = 0; i < gap; i++) { week.push(''); } for (let i = 1; i <= days; i++) { week.push(i); if ((gap + i) % 7 === 0) { calendar.push(week); week = []; } } if (week.length) { calendar.push(week); } this.calendar = calendar; }, selectDate(day) { // 处理日期选择逻辑 } } }; </script> <style scoped> .calendar { display: inline-block; padding: 10px; border: 1px solid #ccc; } .calendar h2 { margin: 0 0 10px; text-align: center; } .calendar table { width: 100%; table-layout: fixed; } .calendar th, .calendar td { padding: 5px; text-align: center; } .calendar td { cursor: pointer; } .calendar .selected { background-color: #ccc; } </style>
<template> <div> <Calendar></Calendar> </div> </template> <script> import Calendar from '@/components/Calendar'; export default { components: { Calendar } }; </script>
Through the above steps, we have implemented a basic calendar selection component. Users can click on a date to select a date, and the selected date will have a special style.
You can add more functions to the calendar component according to actual needs, such as limiting the optional date range, adding event markers, etc. Through the powerful features and component-based development of the Vue framework, we can efficiently implement calendar selection effects and improve user experience.
The above is the detailed content of How to use Vue to implement calendar selection effects. For more information, please follow other related articles on the PHP Chinese website!