I have buttons to set different dates (one for tomorrow and one for in a week) and have made a function for only calculating business days. So the 'tomorrow' button should show either 'Tomorrow' or 'Monday' and the 'week' button should either show 'in 7 days', 'in 8 days' or 'in 9 days' depending on what day of the week it currently is.
These are my two buttons:
<v-btn
:value="dates[0]"
>
{{ buttonText }}
</v-btn>
<v-btn
:value="dates[1]"
>
{{ buttonText }}
</v-btn>
This is my computed for the different dates to postpone and this works just fine:
postponeDays(): DateTime[] {
const today = DateTime.local()
return [
onlyBusinessDays(today, 1),
onlyBusinessDays(today, 7),
]
},
The onlyBusinessDays function looks like this:
export const onlyBusinessDays = (date: DateTime, nrOfDays: number): DateTime => {
const d = date.startOf('day').plus({ days: nrOfDays })
const daysToAdd = d.weekday === 6 ? 2 : d.weekday === 7 ? 1 : 0
return d.plus({ days: daysToAdd })
}
And here is my computed for getting the button text that is not working and I need help with:
buttonText(): DateTime | string {
if (!this.dates[1]) {
if (DateTime.local().plus({ days: 7 }).hasSame(this.dates[1], 'day')) {
return 'in 7 days'
}
if (DateTime.local().plus({ days: 8 }).hasSame(this.dates[1], 'day')) {
return 'in 8 days'
} else return 'in 9 days'
} else {
if (DateTime.local().plus({ days: 1 }).hasSame(this.dates[0], 'day')) {
return 'Tomorrow'
} else return 'Monday'
}
},
I've tried doing the computed for the button text in many different ways but I always end up getting the exact same text for both buttons which feels weird since the postpone function for actually getting the correct dates is working perfectly fine. Anyone that knows what I'm doing wrong? :)
Make buttonText a method instead, so you can put {{ buttonText(dates[0]) }} and {{ buttonText(dates[0]) }}.
As in the Vue docs on computed properties:
Instead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed.
Your two v-btn elements aren't evaluated with different scopes, so there's no reason for Vue to believe that buttonText will have different values in both cases. What you want conceptually is for buttonText to return different values based on the date you pass in, which fits much closer to a method as far as Vue is concerned.
As on the methods page of the guide:
It is also possible to call a method directly from a template. As we'll see shortly, it's usually better to use a computed property instead. However, using a method can be useful in scenarios where computed properties aren't a viable option.