首页 > 解决方案 > 为什么计算内部的异步会产生无限循环(vue)?

问题描述

我计算的组件是这样的:

export default {
  computed: { 
    dataDoctorPerPage: async function () {
        const start = this.pagination.page * this.pagination.rowsPerPage - this.pagination.rowsPerPage;
        const end = start + this.pagination.rowsPerPage - 1;
        const doctors = this.dataDoctor
        const newDoctors = {}
        let key = 0
        for(let item in doctors) {
            if(key >= start && key <= end) {
                for (let i = 0; i < doctors[item].length; i++) {
                    const params = {
                        hospitalId: doctors[item][i].hospital_id,
                        doctorId: doctors[item][i].doctor_id,
                    }
                    await this.getDataSchedule(params) /* call async */
                    // console.log(this.dataSchedule)
                }
                newDoctors[item] = doctors[item]
            }
            key++
        }
        return newDoctors
    }
  }
}

如果调用 dataDoctorPerPage 它将运行脚本

await this.getDataSchedule(params)将通过 vuex 存储调用 async/api。我的问题就在那里。当我打电话时await this.getDataSchedule(params),它会不停地循环

我的 vuex 商店是这样的:

const actions = {
  async getDataSchedule ({ commit }, payload) {
    const result = await api.getDataSchedule(payload)
    const items = result.data
    commit('setDataSchedule', { items: items })
  },
}

我怎么解决这个问题?

计算中是否不能运行异步?

标签: vue.jsvuejs2async-awaitvue-componentvuex

解决方案


计算不应该使用async. 如果你想这样做,你需要另一个库。https://alligator.io/vuejs/async-computed-properties/

但是您想要做的是使用异步方法(在组件或商店中)并将数据设置在某处(在组件的数据或商店的状态中),然后让您的计算值引用它。


推荐阅读