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?
JavaScript
x
22
22
1
<ul class="time-list">
2
<li style="margin-right:2px;"><a href="#" @click="addTime(15)">+15m</a></li><span>|</span>
3
<li style="margin-right:2px;"><a href="#" @click="addTime(30)">+30m</a></li><span>|</span>
4
<li style="margin-right:2px;"><a href="#" @click="addTime(45)">+45m</a></li><span>|</span>
5
<li style="margin-right:2px;"><a href="#" @click="addTime(60)">+1h</a></li><span>|</span>
6
<li><a href="#">---</a></li>
7
</ul>
8
9
export default {
10
data () {
11
return {
12
timeSpent: '0m',
13
}
14
},
15
16
methods: {
17
addTime(time){
18
this.timeSpent = time;
19
},
20
}
21
}
22
Advertisement
Answer
Start with timeSpent at 0
JavaScript
1
4
1
return {
2
timeSpent: 0,
3
}
4
set your function to add the new value to your counter
JavaScript
1
4
1
addTime(time){
2
this.timeSpent += time;
3
},
4
and to format Computed Property
JavaScript
1
6
1
computed: {
2
timeToDisplay(){
3
return `${Math.floor(this.timeSpent/60)}h${this.timeSpent % 60}m`;
4
},
5
}
6
finally to display
JavaScript
1
2
1
{{ timeToDisplay }}
2