我在Vue js中工作的代码:
async mounted() {
const token = this.$store.getters.loggedUser.token;
incidents.getIncidentById(token, this.incidentId).then((resp) => {
this.incidentData = resp.data;
});
incidents.getAllCriteria(token, this.incidentId)
.then(resp => {
this.allCriteria = resp.data;
})
.then(() => {
this.sortAscendingByViolationCriteriumAndFactor();
this.setFactorCheckboxes();
})
.then(() => {
this.allCriteria.forEach(criteria => {
criteria.violationFactors.forEach(factor => {
this.setStateOfTheSameFactorsWithPlusAndMinus(factor);
});
});
});
},
能否请您解释一下为什么以下版本的版本不起作用?我的意思是方法 setStateOfTheSameFactorsWithPlusAndMinus 在这种情况下不起作用(方法 setStateOfTheSameFactorsWithPlusAndMinus 已从这段代码中删除,并移至方法 setFactorCheckboxes ):
async mounted() {
const token = this.$store.getters.loggedUser.token;
incidents.getIncidentById(token, this.incidentId).then((resp) => {
this.incidentData = resp.data;
});
incidents.getAllCriteria(token, this.incidentId)
.then(resp => {
this.allCriteria = resp.data;
})
.then(() => {
this.sortAscendingByViolationCriteriumAndFactor();
this.setFactorCheckboxes();
})
},
methods: {
setFactorCheckboxes() {
this.allCriteria.forEach(criteria => {
criteria.violationFactors.forEach(factor => {
this.selectDegree(factor);
this.setStateOfTheSameFactorsWithPlusAndMinus(factor); //doesn't work here!!!
});
this.updateScoreForCriteria(criteria);
});
}
setStateOfTheSameFactorsWithPlusAndMinus(factor) {
if (factor.factor.includes('(+)') || factor.factor.includes('(-)')) {
let checkbox = document.getElementById('checkbox' + factor.factor);
let factorName = factor.factor;
let factorType = factorName.slice(factorName.length - 3, factorName.length);
let checkboxBasicName = factorName.slice(0, factorName.length - 3);
let checkboxToFindAndChangeState = checkboxBasicName.concat(factorType === '(+)' ? '(-)' : '(+)');
let checkboxToDisable = document.getElementById('checkbox' + checkboxToFindAndChangeState);
if (checkbox.checked) {
checkboxToDisable.disabled = true;
} else {
checkboxToDisable.disabled = false;
}
}
},
这很奇怪! “不起作用”表示加载的页面行为非常难以预测-似乎并非所有数据都已加载,并且setStateOfTheSameFactorsWithPlusAndMinus方法无法正确检查某些复选框
答案 0 :(得分:1)
与其调用async mounted
(因为生命周期挂钩仅是同步的而无法完成),不如通过这种方式从挂载中调用异步方法(记住,异步始终需要等待以返回promise):
mounted () {
this.functionBlah();
}
...
methods: {
async functionBlah () {
await actionX()
.then(actionY)
.then(actionZ)
.catch(err => console.log(err))
}
}