
一段 vue3 代码中使用 computed 导致了栈溢出,原因不明确。
// index.vue
<custom-calendar :check-date="checkdate" class="calendar-box" />
// customcalendar.vaue
<script lang="ts" setup>
const props = defineprops({
checkdate: {
type: array,
default() {
return [];
},
},
});
const mindate = computed(() => {
if (props.checkdate.length) {
let newarr = props.checkdate.sort((a, b): number => a.gettime() - b.gettime());
return new date(+newarr[0] as number);
} else {
return new date();
}
});
const maxdate = computed(() => {
if (props.checkdate.length) {
let newarr = props.checkdate.sort((a, b): number => b.gettime() - a.gettime());
return new date(+newarr[0] as number);
} else {
return new date();
}
});
const curyear = ref<number>(new date().getfullyear());
const curmonth = ref<number>(new date().getmonth());
watch(() => maxdate.value, (newval: date | null) => {
if (newval) {
curyear.value = newval.getfullyear();
curmonth.value = newval.getmonth();
}
}, {
immediate: true,
});
</script>该问题是由相互依赖的 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 属性使用它,从而避免了无限循环。
以上就是Vue3 computed 属性相互依赖导致栈溢出?如何解决?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号