Skip to content
Advertisement

Vue, adding/incrementing time in ‘xhxxm’ format

I’m trying to make a simple interface where a user can increment time using a number of options available in a list. I have it working to set the vue variable as the time that they click on (i.e. if they click ‘+30m’ then the variable reflects 30

However, I’d like to display the variable in the format of XhXXm (so 2 hours and 30 minutes would be 2h30m). The trick is, if they select 15m, then 30m and then 1h, the display should read 1h45m.

How would I alter this in order to actually iterate properly and add up the selections? Should I add it all into minutes and then try to break it out for the UI?

<ul class="time-list">
   <li style="margin-right:2px;"><a href="#" @click="addTime(15)">+15m</a></li><span>|</span>
   <li style="margin-right:2px;"><a href="#" @click="addTime(30)">+30m</a></li><span>|</span>
   <li style="margin-right:2px;"><a href="#" @click="addTime(45)">+45m</a></li><span>|</span>
   <li style="margin-right:2px;"><a href="#" @click="addTime(60)">+1h</a></li><span>|</span>
   <li><a href="#">---</a></li>
 </ul>

export default {
  data () {
    return {
        timeSpent: '0m',
    }
  },

  methods: {
    addTime(time){
       this.timeSpent = time;
    },
  }
}

Advertisement

Answer

Start with timeSpent at 0

return {
    timeSpent: 0,
}

set your function to add the new value to your counter

addTime(time){
    this.timeSpent += time;
},

and to format Computed Property

computed: {
    timeToDisplay(){
        return `${Math.floor(this.timeSpent/60)}h${this.timeSpent % 60}m`;
    },
}

finally to display

{{ timeToDisplay }}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement