How can i do an equivalent JS for in vue? (Increments in n numbers)

Viewed 84

i'm trying to make a select with numbers skipped by 15 units (It's a select of minutes: 0 minutes, 15 minutes, 30 minutes, 45 minutes), i've made it using EJS:

<% for(let x = 0; x < 60; x+= 15) { %>
   <option value="<%= x %>"><%= x %> minutes</option>
<% } %>

It works in EJS, but now i'm migrating that component to a Vue 3 component, but i don't know how can i do a for like that, that for is skipping by 15 units, in vue i just can use a for skipping 1 unit:

<option v-for="i in 60" :key="i" :value="i">{{ i }} minutes</option>

So how can i "translate" that EJS code to Vue? Thanks a lot!

2 Answers

Commentary

Because this only has 4 possible values, I would probably just hard-code them in a util library and import them into the components I needed them

Solution

I'd use a computed property to handle this:

new Vue({
  computed: {
    timeIntervals() {
      let time = 0;
      let ret = [];

      while (time < 60) {
        ret.push(time);
        time += 15;
      }

      return ret;
    }
  },
}).$mount('#root');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root">
  <select>
    <option v-for="interval in timeIntervals" :key="interval" :value="interval">{{interval}}</option>
  </select>
</div>

I generate the intervals array in the computed property, and then use that inside of the template to display each interval

Solution w/ Vue 3

const App = {
  computed: {
    timeIntervals() {
      let intervals = [];

      for (let i = 0; i < 60; i += 15) {
        intervals.push(i);
      }

      return intervals;
    },
  }
}

Vue.createApp(App).mount('#root')
<script src="https://unpkg.com/vue@next"></script>


<div id="root">
  <select>
    <option v-for="interval in timeIntervals" :key="interval" :value="interval">{{interval}}</option>
  </select>
</div>

What you can do is use the Modulo operator which will return true or false based on a divisional outcome

<option v-for="i in 60" v-if="i % 15 == true">{{ i - 1 }} minutes</option>

This loop will through each value 1...60 and divide it by 15 only printing the result if it's true.

It's commonly bad practice to use v-for and v-if at the same time, but this will get you where you want to be.

outcome:

0 minutes
15 minutes
30 minutes
45 minutes
Related