Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Years from 1900 to current year with VueJS

I am creating a registration form with VueJS! The user has to enter his/her date of birth.

So, how can I generate years starting from 1900 to current year in <select> element?

I tried this:

new Vue ({
  el: '.container',
  methods: {
    getCurrentYear() {
      return new Date().getFullYear();
    }
  }
});
<div class="container">
  <select id="dob">
    <option value="0">Year:</option>
    <option v-for="year in getCurrentYear()" :value="year">{{ year }}</option>
  </select>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

However, the year starts from 1 in this case. So, how can I loop through <option> with the year starting from 1900?

like image 789
Sanjay Avatar asked Apr 07 '18 06:04

Sanjay


1 Answers

  1. Don't use a method in the loop, use a computed property instead.
  2. Don't use v-if in a v-for element. It's bad!

new Vue ({
  el: '.container',
  computed : {
    years () {
      const year = new Date().getFullYear()
      return Array.from({length: year - 1900}, (value, index) => 1901 + index)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div class="container">
<select id="dob">
  <option value="0">Year:</option>
  <option v-for="year in years" :value="year">{{ year }}</option>
</select>
</div>
like image 90
Frondor Avatar answered Nov 06 '22 00:11

Frondor