I've started learning Vuejs and as a newbie i've started with some basic stuff like fetching data from an API and presenting data to a template. It works fine till now but i had an idea of setting a progress bar. So every time a record is added in db, then increase progress in percentage meaning one record in db 1%, 2 records 2% and so on until reaching 100%. My problem is to calculate the percentage, I did some research but i couldn't find something similar to this, so if someone can give me some instructions on how to do it, i would be very pleased! Below is my code so far.
<div >
<div >Progress of Goal:
<span >{{ salaries.length }}% - {{ salaries.length }} Salaries submitted</span>
</div>
<div >
<div style="width: 4%"> {{ salariesLength }}%</div>
</div>
</div>
</div>
<div v-bind:>
<div ></div>
</div>
<div
v-for="salary in salaries"
v-bind:key="salary.id"
>
<SalaryItem :salary="salary" />
/div>
<script>
import axios from 'axios'
import SalaryItem from '@/components/SalaryItem.vue'
export default {
data() {
return {
salaries: [],
}
},
computed: {
salariesLength() {
return this.salaries.length
}
},
components: {
SalaryItem
},
async mounted() {
this.$store.commit('setIsLoading', true)
await axios
.get('/salaries/')
.then(response => {
this.salaries = response.data
})
.catch(error => {
console.log(error)
})
this.$store.commit('setIsLoading', false)
}
}
</script>
CodePudding user response:
Not sure to understand on what total the percentage in calculated on the example you provided : you seem to fetch all data at once in your mounted hook, on what base do you want to define percentage ?
Besides that, you can render a progress bar by setting dynamically the width property of your progress bar element using a computed :
computed: {
progressStyle() {
return {
width: this.progress "%",
};
},
},
In your template, you just declare 2 elements : one container and inside your progress bar that will have a width expressed in % of the container:
<div >
<div :style="progressStyle"></div>
</div>
Through the :style
attribute, the width of the div will be x% depending on the progress
variable that you need to define to handle the logic to calculate the percentage. Again, Im not sure where you get your total from, so we'll have to assume a totalSalaries
exists somewhere :
computed: {
progress(){
return this.salaries.length / this.totalSalaries * 100
},
progressStyle() {
return {
width: this.progress "%",
};
},
},