Sometimes we may need to create years list (past) for something like a date of birth selection from a drop-down menu (select / option).
We can create a year list dynamically by using a start year. For instance, if we use a start year as 1990, we can create a list like 1990, 1991 … 2022 (all the way up to the current year).
Here’s how we can do that in the Vue 3 Composition API:
<script setup>
import { ref, onMounted } from 'vue'
const yearsList = ref([])
const selectedYear = ref(null)
const getYearsList = () => {
const startYear = 1990;
const endYear = new Date().getFullYear();
for (let i = endYear; i >= startYear; i--) {
yearsList.value = [...yearsList.value, i]
}
}
onMounted(() => {
getYearsList()
})
</script>
<template>
<div>
<h1>
Years list
</h1>
<p>
<select v-model="selectedYear">
<option v-for="(year, y) in yearsList" :key="y" :value="year">
{{year}}
</option>
</select>
</p>
<p>
Selected year: {{selectedYear}}
</p>
</div>
</template>
Code language: HTML, XML (xml)
In the above code, we have dynamically created a years list as a dropdown selection input. The reactive state yearsList contains all the year numbers as an array. selectedYear contains the value of whichever year we choose from the dropdown menu.
Here’s how the above code would look like in action: