vue3 computed 中的代码导致栈溢出?
问题:
一段 vue3 代码中使用 computed 导致了栈溢出,原因不明确。
// index.vue// customcalendar.vaueconst 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(new date().getfullyear());const curmonth = ref(new date().getmonth());watch(() => maxdate.value, (newval: date | null) => { if (newval) { curyear.value = newval.getfullyear(); curmonth.value = newval.getmonth(); }}, { immediate: true,});
登录后复制
答案:
该问题是由相互依赖的 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的变化,并更新sortedCheckDateswatch(() => 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 属性相互依赖导致栈溢出?如何解决?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2651855.html