vue3 computed中的代码导致栈溢出?
// index.vue
<custom-calendar :check-date="checkDate" class="calendar-box" />
// CustomCalenda.vaue
<script lang="ts" setup>
const props = defineProps({
checkDate: {
type: Array,
default() {
return []
}
}
})
const minDate = computed(() => {
debugger
if (props.checkDate.length) {
let newArr = props.checkDate.sort((a:any, b:any):number => a.getTime() - b.getTime())
return new Date(+newArr[0] as number)
} else {
return new Date()
}
})
const maxDate = computed(() => {
debugger
if (props.checkDate.length) {
let newArr = props.checkDate.sort((a:any, b:any):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) => {
debugger
if (newVal) {
curYear.value = newVal.getFullYear()
curMonth.value = newVal.getMonth()
}
}, {
immediate: true
})
这段代码控制台报栈溢出我打了断点,发现代码会在两个computed中无限的执行下去,导致栈溢出,但是我没有找到原因为什么会循环执行?
回复
1个回答
test
2024-06-19
在Vue中,使用computed属性时,如果依赖的响应式属性发生变化,computed
属性会自动重新计算。在你提供的代码中,minDate
和maxDate
两个computed
属性都依赖于props.checkDate
数组。如果checkDate
数组发生变化,这两个属性都会重新计算,而每个computed
属性的计算过程中又都会对checkDate
数组进行排序操作,这可能导致它们相互触发重新计算,从而形成无限循环。
可以如下面这样修改看看:
<script lang="ts" setup>
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());
});
</script>
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容