
vue3 中 computed 中的代码导致栈溢出分析
代码中存在栈溢出,是因为 computed 属性的无限递归调用。
computed 属性是 vue3 中的一种响应式函数,当其依赖的响应式属性发生变化时,会自动重新计算。在这个例子中,mindate 和 maxdate 两个 computed 属性都依赖于 props.checkdate 数组。
当 props.checkdate 数组发生变化时,mindate 和 maxdate 都会重新计算,但在此过程中,它们又会对 checkdate 数组进行排序,这会导致一个无限循环:
立即学习“前端免费学习笔记(深入)”;
为了解决这个问题,可以将排序后的 checkdate 数组保存在一个响应式变量中。这种情况下,称为 sortedcheckdates。然后,mindate 和 maxdate 可以使用 sortedcheckdates 计算,从而避免了无限循环。
以下是如何实现这些修改:
<script lang="ts" setup>
// ...
// 新增一个响应式属性来存储排序后的数组
const sortedCheckDates = ref([]);
const minDate = computed(() => {
if (sortedCheckDates.value.length) {
return new Date(sortedCheckDates.value[0].getTime());
} else {
return new Date();
}
});
const maxDate = computed(() => {
if (sortedCheckDates.value.length) {
return new Date(sortedCheckDates.value[sortedCheckDates.value.length - 1].getTime());
} else {
return new Date();
}
});
// 监听 checkDate 的变化,并更新 sortedCheckDates
watch(() => {
sortedCheckDates.value = sortCheckDate(props.checkDate);
}, {
deep: true,
});
// ...
// 在 mounted 生命周期中对 sortedCheckDates 进行初始化
onMounted(() => {
sortedCheckDates.value = sortCheckDate(props.checkDate);
});
function sortCheckDate(dates) {
return dates.sort((a, b) => a.getTime() - b.getTime());
}
</script>以上就是Vue3 computed 中的无限递归调用如何解决?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号