Vue3 computed属性导致栈溢出:如何避免minDate和maxDate的无限循环?

vue3 computed属性导致栈溢出:如何避免mindate和maxdate的无限循环?

Vue3 computed属性导致栈溢出:巧妙避免minDate和maxDate无限循环

在Vue3开发中,computed属性是提升代码可读性和维护性的利器。然而,不当使用可能导致栈溢出等问题。本文将分析一个minDatemaxDate计算属性导致栈溢出的案例,并提供有效的解决方案。

问题描述:

以下Vue3代码片段中,minDatemaxDate计算属性的逻辑导致栈溢出。

立即学习“前端免费学习笔记(深入)”;


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 });

调试发现,minDatemaxDate无限循环,原因在于它们依赖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]创建数组的浅拷贝,避免直接修改原始数据。

这个改进的方案有效地解决了minDatemaxDate计算属性的无限循环问题,确保了代码的稳定性和可靠性。

以上就是Vue3 computed属性导致栈溢出:如何避免minDate和maxDate的无限循环?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1502868.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月20日 01:19:38
下一篇 2025年12月20日 01:19:47

相关推荐

发表回复

登录后才能评论
关注微信