使用Vue写一个日期选择器

以下是一个使用Vue编写的日期选择器的示例代码:

<template>
  <div>
    <input type="text" v-model="selectedDate" @click="showDatePicker" placeholder="选择日期">
    <div v-if="isDatePickerVisible" class="date-picker">
      <div class="header">
        <button @click="prevMonth"><</button>
        <span>{
   
   { currentMonth }}</span>
        <button @click="nextMonth">></button>
      </div>
      <div class="days">
        <div v-for="day in daysInMonth" :key="day" class="day" @click="selectDate(day)">
          {
   
   { day }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedDate: '',
      currentMonth: '',
      isDatePickerVisible: false
    };
  },
  computed: {
    daysInMonth() {
      const date = new Date(this.currentMonth);
      const year = date.getFullYear();
      const month = date.getMonth();
      const daysInMonth = new Date(year, month + 1, 0).getDate();
      return Array.from({ length: daysInMonth }, (_, index) => index + 1);
    }
  },
  methods: {
    showDatePicker() {
      this.isDatePickerVisible = true;
      this.currentMonth = new Date();
    },
    prevMonth() {
      const prevMonth = new Date(this.currentMonth);
      prevMonth.setMonth(prevMonth.getMonth() - 1);
      this.currentMonth = prevMonth;
    },
    nextMonth() {
      const nextMonth = new Date(this.currentMonth);
      nextMonth.setMonth(nextMonth.getMonth() + 1);
      this.currentMonth = nextMonth;
    },
    selectDate(day) {
      const selectedDate = new Date(this.currentMonth);
      selectedDate.setDate(day);
      const formattedDate = selectedDate.toLocaleDateString('en-US');
      this.selectedDate = formattedDate;
      this.isDatePickerVisible = false;
    }
  }
};
</script>

<style scoped>
.date-picker {
  position: absolute;
  top: 40px;
  left: 0;
  background: #fff;
  border: 1px solid #ccc;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 10px;
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
}

.days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

.day {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  height: 40px;
  border: 1px solid #ccc;
}

input {
  padding: 5px;
  border: 1px solid #ccc;
}
</style>

在上述代码中,我们使用了一个input元素来显示和输入选中的日期,并使用一个div元素作为日期选择器的容器。当点击input元素时,会显示日期选择器。日期选择器的实现参考了当前月份的日历,并提供了上一个月和下一个月的按钮来切换月份。

在Vue组件中,我们使用了data属性来定义必要的数据,如选中的日期、当前月份,以及一个表示日期选择器是否可见的标志。computed属性用于计算当前月份的天数,并将其渲染到日期选择器中。methods属性定义了一些用于展示和操作日期选择器的方法。

通过上述代码,您可以将日期选择器组件集成到您的Vue应用程序中,并使用v-model指令来进行双向数据绑定,以获取选中的日期。

猜你喜欢

转载自blog.csdn.net/m0_74801194/article/details/135422748