vue3 computed 中的循环执行导致栈溢出
在 vue3 中使用 computed 属性时,一个常见的错误是代码中的循环执行,导致栈溢出。让我们分析一下这个问题的原因和相应的解决方案。
在你提供的代码中,mindate和maxdate两个 computed 属性都依赖于 props.checkdate 数组。当 checkdate 数组发生变化时,这两个属性都会重新计算。然而,在计算过程中,这些属性会对 checkdate 数组进行排序,这可能导致它们相互触发重新计算,从而形成无限循环。
为了解决这个问题,我们可以采取以下步骤:
立即学习“前端免费学习笔记(深入)”;
使用 ref 来存储排序后的数组。在 checkdate 发生变化时,更新排序后的数组。在 computed 属性中使用排序后的数组,而不是对 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());});
登录后复制
通过这种方式,我们解决了 computed 属性中的无限循环,避免了栈溢出错误。
以上就是Vue3 computed 中的循环执行如何避免栈溢出?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2651761.html