im fetching data with;
data() {
return {
staffs: "",
salaries:0,
loading:true,
};
},
methods: {
async getStaffs() {
const result = await axios.get(
"/api/staffs/"
);
this.staffs = result.data
this.loading = false
},
totalSalary(){
for(var i = 0 ;i++;i<this.staffs.length){
this.salaries += this.staffs[i].job.salary
}
},
mounted() {
this.getStaffs()
this.totalSalary()
},
}
I want to calculate total salaries after fetching data and render it like
<span >Total Salary: {{salaries}}</span>
What is the correct way to do it? I don't want to use timeout or smt like that.
You can simply use async/await
in your mounted
hook
data() {
return {
staffs: "",
salaries:0,
loading:true,
};
},
methods: {
async getStaffs() {
const result = await axios.get(
"/api/staffs/"
);
this.staffs = result.data
this.loading = false
},
totalSalary(){
for(var i = 0 ;i++;i<this.staffs.length){
this.salaries += this.staffs[i].job.salary
}
},
async mounted() {
await this.getStaffs() // wait for getStafss to finish executing
this.totalSalary()
},
However, in your case, I would recommend using a computed
prop to calculate totalSalary