我正在使用 Vue 3、Vite 编写一个小网站。我有一个组件Holidays
,可以显示特定一天(今天)的假期列表。
<script setup lang="ts">
import { computed } from 'vue'
import { getCurrentDay, getCurrentMonth, getHolidaysByDate } from '@/utils'
const today = new Date()
const currentDay = getCurrentDay(today)
const currentMonth = getCurrentMonth(today)
const currentHolidays = computed(() => getHolidaysByDate(currentDay, currentMonth))
</script>
<template>
<div class="holidays-list gc-font-body">
<template v-if="currentHolidays.length > 0">
<div
v-for="(holiday, index) in currentHolidays"
:key="index"
:class="['holiday', index === 0 ? 'holiday-important' : '']"
>
<div class="holiday-title">{{ holiday.title }}</div>
<div class="gc-font-gray">{{ holiday.description }}</div>
</div>
<div class="holiday holiday-additional gc-font-body-m gc-font-gray gc-align-center">
Посмотреть все
</div>
</template>
<div v-else class="gc-font-body gc-font-gray gc-align-center">
К сожалению, мы не нашли информацию о праздниках в этот день. Если у вас есть предложение
по добавлению праздника, пожалуйста, нажмите на кнопку «Добавить праздник» в шапке сайта.
</div>
</div>
</template>
ChatGPT 为我提供了这种逻辑的确切实现,其中computed
只有currentHolidays
。然而,在各种来源中,并且定期地,同一个 ChatGPT 建议我将变量包装today
在ref
—中const today = ref(new Date())
,并将所有后续变量包装在 中computed
。从逻辑上讲,内容每天在页面重新加载时更新一次。据我所知,“computed
当您需要跟踪变量的变化,然后执行计算或其他操作(取决于跟踪的变量)时建议使用,其结果将以另一个变量的形式存储。”
我想更详细地了解这一点。