Search code examples
vue.jsfor-loopv-for

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


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!


Solution

  • 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>