Retrieve a variety of outputs from computed properties in Vue

I have created buttons to select different dates (one for tomorrow and one for next week) with a function that calculates only business days. The 'tomorrow' button should display either 'Tomorrow' or 'Monday', while the 'week' button should show 'in 7 days', 'in 8 days', or 'in 9 days' depending on the current day of the week.

Here are the two buttons:

        <v-btn
            :value="dates[0]"
        >
            {{ buttonText }}
        </v-btn>
        <v-btn
            :value="dates[1]"
        >
            {{ buttonText }}
        </v-btn>

This is the computed function I used to calculate the postponed dates, which is functioning correctly:

postponeDays(): DateTime[] {
    const today = DateTime.local()
    return [
        onlyBusinessDays(today, 1),
        onlyBusinessDays(today, 7),
    ]
},

The implementation of the `onlyBusinessDays` function is as follows:

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

Now, here's where I'm struggling - the computed function to determine the button text:

    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 attempted different approaches to this computed function, but I keep getting the same text for both buttons. It's puzzling because the postpone function for obtaining the correct dates is working flawlessly. Can anyone identify what I might be doing incorrectly? :)

Answer №1

Transform buttonText into a method for more flexibility, allowing you to utilize {{ buttonText(dates[0]) }} and {{ buttonText(dates[0]) }}.

Referencing the Vue documentation on computed properties:

Instead of using a computed property, consider defining the same function as a method. Ultimately, both approaches yield the same result. However, the key distinction is that computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when any of its reactive dependencies change.

Since your two v-btn elements are not assessed under different scopes, Vue does not perceive any reason for buttonText to have varying values in each instance. Ideally, you want buttonText to provide distinct outcomes depending on the date parameter, aligning closely with what Vue considers a method.

According to the methods section of the guide:

It's feasible to directly invoke a method from within a template. In most cases, however, using a computed property is preferred. Yet, resorting to a method can prove beneficial in scenarios where computed properties are not practical.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the player's URL by clicking on an item in the list

I am looking to create a channel website where the streaming URL changes without reloading the page when the user clicks on a channel name. Here is the code I currently have: <div class="player-section"> <div class="container"> ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

Can someone help me figure out how to increase the values of two specific attributes within a class?

Currently facing a challenge with adjusting the number of likes and comments using increment for properties 'numberOfLikes' and 'comments'. Unsure whether to utilize a for loop or just the increment operator. Still new to coding, so apo ...

Yeoman - Storing global settings efficiently

I have recently developed a Yeoman generator and am now looking to incorporate prompts for certain global configurations. My goal is to have the generator prompt users for their GitHub username and token during the initial run, and then somehow store this ...

Using DaisyUI (Tailwind CSS) to create modals in Vue.js 3

Currently, I am exploring DaisyUI within Vue.js 3. (migrating an existing Vue+Bootstrap application to Tailwind CSS). I appreciate that DaisyUI avoids using complex JavaScript in the background, but it seems like there is some mysterious CSS magic happenin ...

Issues with Bootstrap's hamburger menu not functioning properly when clicked

Can't seem to get my hamburger button working. I've followed the bootstrap documentation and ensured that Bootstrap and jQuery are in the correct order, but still no luck. Any suggestions on what could be causing this issue? Are my links misplace ...

Turn off Vuetify designs specifically for Katex elements - Using common classes such as .accent can cause problems with styles

I have encountered an issue while using Katex with Vuetify. Certain classes such as accent or overline are causing conflicts between the two libraries, resulting in strange styling inconsistencies. For example, the overline characters are inheriting the ac ...

Is there a way to display incoming chat messages on the chat box without requiring a page refresh using socket.io?

Having trouble resolving an issue with my application hosted on wpengine, built using WordPress, vue.js, and socket.io for chat functionality. The main concern is that new messages posted in the chatbox do not display until the page is refreshed. I'm ...

Trouble transferring data between sibling components in Vue.js

In my setup, there are three components where one acts as the parent to the others. I am attempting to pass an object named talk between sibling components by emitting it through an event from FollowedBrowser to LeftBar, and then passing it via props from ...

Issue with updating the div to show the user's submission form in Angular is causing difficulties

After a user submits a form, I would like to display their submission by hiding the form area and showing the response in that same area. Upon submitting the form, my goal is to show a mat-spinner until a response is received from the server. The compone ...

Finding ways to incorporate multiple Vue projects into a single Laravel project can be a challenging yet rewarding

I am working on a Laravel project that will have multiple backends, and I also need to implement multiple frontends using Vue in another Laravel project. For the frontend integration, I plan to create separate frontends within the resource/js folder such ...

Best practices for implementing JavaScript in JSP pages

After researching various sources, I have come across conflicting opinions on the topic which has left me feeling a bit confused. As someone new to web programming using java EE, I am looking to integrate javascript functions into my code. It appears that ...

How can I display the values stored in an array of objects in Angular 2

I need help printing out the value of id from an array that is structured like this: locations = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)'}, {id: '2', lat: 51.523 ...

The issue arises when the input type=file data is not being successfully sent to the PHP page through the implementation

Currently, I am encountering an issue with validating file uploads in an HTML form using a jQuery plugin. The validation process works fine for empty files as it displays an error message. However, when the uploaded file has a different extension than expe ...

Linking a background image in the body to a specific state in next.js

My aim is to create a pomodoro timer using Next.js and I'm trying to link the body's background image to a state. However, my code isn't functioning properly. This is the code I used to update the body style: import { VscDebugRestart } from ...

Discovering the most recent messages with AJAX

I'm feeling a bit lost on this topic. I'm looking to display the most recent messages stored in the database. (If the messages are not yet visible to the user) Is there a way to achieve this without constantly sending requests to the server? (I ...

Unable to reinitialize MUI DatePicker after keydown event

Encountering an unusual behavior that defies explanation has left me puzzled. You can explore the code sandbox here. I am attempting to enable resetting a readOnly field by pressing DEL or BACKSPACE, but it seems to be ineffective. Oddly enough, I can suc ...

How can I execute a StoredProcedure using JavaScript?

I have a form with an email field and label <asp:TableRow runat="server"> <asp:TableCell runat="server"> <asp:TextBox runat="server" ID="txtUserEmail" onfocusout="emailVerification()" CssClass="forTe ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

How can I properly define the type for an object in Typescript where the key is a string and the value is an array of objects?

let colors = { "red" : [ { title: "red", summary : "red is ...", image : "image of red", // optional link : "https:// ..." }, { ...