
vue3 computed 中的代码导致栈溢出?
问题:
一段 vue3 代码中使用 computed 导致了栈溢出,原因不明确。
// index.vue// customcalendar.vaue
答案:
该问题是由相互依赖的 computed 属性导致的无限循环引起的。
mindate 和 maxdate computed 属性都依赖于 props.checkdate 数组。如果 checkdate 数组发生变化,这两个属性都会重新计算。在重新计算过程中,它们又会对 checkdate 数组进行排序,这可能导致它们相互触发重新计算,形成无限循环。
以下是对代码的修改,以解决此问题:
立即学习“前端免费学习笔记(深入)”;
import { ref, computed, watch, onMounted } from 'vue';
const props = defineProps({
checkDate: {
type: Array,
default() {
return [];
},
},
});
// 新增一个响应式属性来存储排序后的数组
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(() => props.checkDate, (newVal) => {
sortedCheckDates.value = newVal.sort((a, b) => a.getTime() - b.getTime());
});
const curYear = ref(new Date().getFullYear());
const curMonth = ref(new Date().getMonth());
watch(() => maxDate.value, (newVal) => {
if (newVal) {
curYear.value = newVal.getFullYear();
curMonth.value = newVal.getMonth();
}
}, {
immediate: true,
});
onMounted(() => {
// 初始化sortedCheckDates
sortedCheckDates.value = props.checkDate.sort((a, b) => a.getTime() - b.getTime());
});此修改通过引入一个额外的响应式属性 sortedcheckdates 来存储排序后的 checkdate 数组,解决了 computed 属性之间的相互依赖性。现在,当 checkdate 数组发生变化时,sortedcheckdates 数组将更新,并由 computed 属性使用它,从而避免了无限循环。










