
Vue3 computed属性导致栈溢出:巧妙避免minDate和maxDate无限循环
在Vue3开发中,computed属性是提升代码可读性和维护性的利器。然而,不当使用可能导致栈溢出等问题。本文将分析一个minDate和maxDate计算属性导致栈溢出的案例,并提供有效的解决方案。
问题描述:
以下Vue3代码片段中,minDate和maxDate计算属性的逻辑导致栈溢出。
立即学习“前端免费学习笔记(深入)”;
<custom-calendar :check-date="checkdate" class="calendar-box"></custom-calendar>
const props = defineProps({
checkdate: {
type: Array,
default: () => []
}
});
const minDate = computed(() => {
if (props.checkdate.length) {
const sortedDates = [...props.checkdate].sort((a, b) => a.getTime() - b.getTime());
return new Date(sortedDates[0].getTime());
} else {
return new Date();
}
});
const maxDate = computed(() => {
if (props.checkdate.length) {
const sortedDates = [...props.checkdate].sort((a, b) => b.getTime() - a.getTime());
return new Date(sortedDates[0].getTime());
} else {
return new Date();
}
});
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 });调试发现,minDate和maxDate无限循环,原因在于它们依赖props.checkdate,而计算过程又通过排序修改了props.checkdate,形成恶性循环。
解决方案:
为了解决这个问题,我们引入一个新的响应式变量来存储排序后的checkdate数组,避免在computed属性中直接修改原始数据。
import { ref, computed, watch, onMounted } from 'vue';
const props = defineProps({
checkDate: {
type: Array,
default: () => []
}
});
const sortedCheckDates = ref([]);
const minDate = computed(() => {
return sortedCheckDates.value.length ? new Date(sortedCheckDates.value[0].getTime()) : new Date();
});
const maxDate = computed(() => {
return sortedCheckDates.value.length ? new Date(sortedCheckDates.value[sortedCheckDates.value.length - 1].getTime()) : new Date();
});
watch(() => props.checkDate, (newVal) => {
sortedCheckDates.value = [...newVal].sort((a, b) => a.getTime() - b.getTime());
}, { immediate: true });
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 });通过sortedCheckDates,我们将排序操作与computed属性计算分离,避免了无限循环。immediate: true确保watch在组件初始化时立即执行一次。 使用[...newVal]创建数组的浅拷贝,避免直接修改原始数据。
这个改进的方案有效地解决了minDate和maxDate计算属性的无限循环问题,确保了代码的稳定性和可靠性。
以上就是Vue3 computed属性导致栈溢出:如何避免minDate和maxDate的无限循环?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号