如何使Vue.js月下拉列表?



这在我的测试项目中正确工作,但我不知道这是如何完成的。换句话说,我不明白这是如何构建与Vue.js。这看起来有点复杂。我觉得这个可以简化。如果有什么建议可以帮助你,那就太好了。

基本上,我想创建一个从01到12个月的信用卡到期列表。

< script >
export default {
methods: {
minCardMonth() {
if (this.cardYear === this.minCardYear) return new Date().getMonth() + 1;
return 1;
}
}
} <
/script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<select class="input-control">
<option disabled selected>-- Month --</option>
<option v-bind:value="n < 10 ? '0' + n : n" v-for="n in 12" v-bind:disabled="n < minCardMonth" v-bind:key="n">
{{n
< 10 ? '0' + n : n}} </option>
</select>

这里有一个更高级的代码片段:当用户选择未来的年份和已经超过今年的月份,然后更改回当前年份(月份选择默认为原始值)时,它还处理边缘情况。

整个要点是:有时控制组件的UI (<template>部件)似乎很容易-但将视觉效果与数据解耦总是更好。尝试组织您的代码,以便表示/UI对底层数据的更改做出反应,并控制数据。

在这种情况下,你可能是对的,也许这段代码有点过头了——但说实话,我不会为自己这样做(也许添加TypeScript:))

// generating two digits months numbers
const MONTHS_OF_YEAR = () => {
return Array(12)
.fill(0)
.map((_, i) => {
return {
value: i,
text: ("0" + (i + 1)).slice(-2),
disabled: false,
}
})
}
// the default (unselectable) value in
// the months options:
const DEFAULT_MONTH_VALUE = () => ({
text: "--- Month ---",
value: null,
disabled: true,
})
const DEFAULT_YEAR_VALUE = () => [
"--- Year ---",
2021,
2022,
2023,
2024,
2025,
]
new Vue({
el: "#app",
data() {
return {
cardYear: DEFAULT_YEAR_VALUE()[0],
cardMonth: DEFAULT_MONTH_VALUE(),
cardYearOptions: DEFAULT_YEAR_VALUE(),
cardMonthOptions: MONTHS_OF_YEAR(),
}
},
computed: {
minCardYear() {
return new Date().getFullYear()
},
minCardMonth() {
return new Date().getMonth()
},
possibleMonths() {
// defaulting to "all months are available"
let returnMonths = [...this.cardMonthOptions]
if (this.cardYear === this.minCardYear) {
returnMonths = this.cardMonthOptions
.map((month, i) => {
if (i < this.minCardMonth) {
return {
...month,
disabled: true,
}
}
return month
})
}
// returning the array that will
// be iterated over - its first
// value is always the default
return [
DEFAULT_MONTH_VALUE(),
...returnMonths,
]
},
},
watch: {
// if cardYear is changed from a future date
// to the current year, it's wise to check
// selected month - maybe we're past that month
cardYear(newVal) {
const selectedMonth = this.possibleMonths.find(month => {
return month.value === this.cardMonth.value
})
if (selectedMonth?.disabled) {
this.cardMonth = DEFAULT_MONTH_VALUE()
}
},
},
template: `
<div>
MinCardYear: {{ minCardYear }}<br />
SelectedCardYear: {{ cardYear }}<br />
SelectedCardMonth: {{ cardMonth.text }}<br />
<select v-model="cardYear">
<option
v-for="(year, i) in cardYearOptions"
:key="year"
:value="year"
:disabled="i === 0"
>
{{ year }}
</option>
</select>
<select v-model="cardMonth">
<option
v-for="month in possibleMonths"
:key="month.value"
:value="month"
:disabled="month.disabled"
>
{{ month.text }}
</option>
</select>
</div>
`
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

最新更新