简体   繁体   English

如何使用 vuejs 对获取的数据使用函数

[英]How can I use functions on fetched data with vuejs

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.我不想那样使用超时或 smt。

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.我不想像那样使用超时或 smt。

You can simply use async/await in your mounted hook您可以简单地在mounted的钩子中使用async/await

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但是,在您的情况下,我建议使用computed道具来计算totalSalary

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM