uiapp使用vue3的语法实现月份选择器
时间: 2024-02-29 18:53:30 浏览: 120
基于vue2.0实现的级联选择器
5星 · 资源好评率100%
好的,以下是一个使用 Vue3 的语法实现月份选择器的示例代码:
```vue
<template>
<div class="month-picker">
<input type="text" v-model="selectedMonth" readonly @click="showPicker" />
<div class="picker" v-show="isPickerVisible">
<div class="header">
<button @click="previousYear"><<</button>
<button @click="previousMonth"><</button>
<span>{{ currentYear }} 年 {{ currentMonth }} 月</span>
<button @click="nextMonth">></button>
<button @click="nextYear">>></button>
</div>
<div class="body">
<div class="month" v-for="(month, index) in months" :key="index" @click="selectMonth(month)">
{{ month }}
</div>
</div>
</div>
</div>
</template>
<script>
import { ref, computed } from 'vue';
export default {
name: 'MonthPicker',
setup() {
const selectedMonth = ref('');
const isPickerVisible = ref(false);
const currentYear = ref(new Date().getFullYear());
const currentMonth = ref(new Date().getMonth() + 1);
const months = computed(() => {
const result = [];
for (let i = 1; i <= 12; i++) {
result.push(`${i} 月`);
}
return result;
});
const showPicker = () => {
isPickerVisible.value = true;
};
const hidePicker = () => {
isPickerVisible.value = false;
};
const previousMonth = () => {
if (currentMonth.value === 1) {
currentMonth.value = 12;
currentYear.value -= 1;
} else {
currentMonth.value -= 1;
}
};
const nextMonth = () => {
if (currentMonth.value === 12) {
currentMonth.value = 1;
currentYear.value += 1;
} else {
currentMonth.value += 1;
}
};
const previousYear = () => {
currentYear.value -= 1;
};
const nextYear = () => {
currentYear.value += 1;
};
const selectMonth = (month) => {
selectedMonth.value = month;
hidePicker();
};
return {
selectedMonth,
isPickerVisible,
currentYear,
currentMonth,
months,
showPicker,
hidePicker,
previousMonth,
nextMonth,
previousYear,
nextYear,
selectMonth,
};
},
};
</script>
<style scoped>
.month-picker {
position: relative;
}
.picker {
position: absolute;
top: 100%;
left: 0;
z-index: 1;
background-color: #fff;
border: 1px solid #ccc;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px;
background-color: #f5f5f5;
}
.header button {
border: none;
background-color: transparent;
font-size: 14px;
cursor: pointer;
}
.body {
display: flex;
flex-wrap: wrap;
padding: 8px;
}
.month {
flex-basis: 25%;
padding: 8px;
text-align: center;
cursor: pointer;
}
.month:hover {
background-color: #f5f5f5;
}
</style>
```
这个月份选择器组件包含一个输入框和一个下拉框,用户可以通过点击输入框来显示下拉框,从而选择一个月份。下拉框显示了当前年份和月份,以及所有的月份选项。用户可以通过点击月份选项来选择一个月份,选择后下拉框会自动隐藏并将选择的月份显示在输入框中。用户还可以通过左右箭头按钮来切换年份和月份。
阅读全文