Display a list of years by iterating over a computed property in Vue JS

Currently, I have a code snippet that displays a list of years. It seems to me that this code is a bit excessive, and I believe that implementing a computed property for validYears would streamline the code and eliminate the need for unnecessary watchers. However, I am struggling to understand how to convert this into a computed property. If anyone could provide an example of how I can create a computed property for valid years while achieving the same result, I would greatly appreciate it.

    onBeforeMount(calculateDateRange)

    watch(() => props.earliestDate, (newValue, prevValue) => {
      calculateDateRange();
    });
    
    watch(() => props.latestDate, (newValue, prevValue) => {
      calculateDateRange()
    });

    const validYears = ref([])
    function calculateDateRange () {
      for(let year = props.latestDate; year >= props.earliestDate; year--){
        validYears.value.push(year)
      }
    }

I opted not to include the remaining code to avoid cluttering the question. In this component, I have a set of props that dictate the values in my for loop.

Answer №1

One way to improve its efficiency is by:

const validYearsList = computed(()=>{
    let yearsArr=[]
    for(let y = props.maxDate; y >= props.minDate; y--){
        yearsArr.push(y)
      }
 
  return yearsArr;

}) 

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

Google Analytics detects an increase in traffic from a specific subdomain

Utilizing Tag Manager, I have successfully added an Analytics tracker to my WordPress site at . However, despite only adding the tracker to the main domain, Analytics is picking up traffic from subdomains like task.mile.app. I am confident that I have onl ...

What is the best way to convert a series of sentences into JSON format?

I'm struggling with breaking down sentences. Here is a sample of the data: Head to the dining room. Open the cabinet and grab the bottle of whisky. Move to the kitchen. Open the fridge to get some lemonade for Jason. I am looking to format the outc ...

The `appendTo` function in Ajax is used to swap out the current element

I have been working on sending form data to a Servlet using JQuery and then receiving the response from the same JQuery. Check out the code snippet below. <%-- Document : index Created on : Feb 23, 2015, 8:18:52 PM Author : Yohan --% ...

Limiting multiple checkbox inputs in a React application can be easily achieved by utilizing React

Trying to create a form where the user can only check three boxes and uncheck them. The decrement on setCurrentData(currentData - 1) is not working as expected. Even after deselecting, the currentData remains at 3, preventing the user from checking any mo ...

Selecting options in table is disrupted by filtering in ng-repeat

My table showcases selectable information, featuring parent rows and child rows. I am seeking a solution where only the parent rows are selectable if they have no children; otherwise, only the child rows should be clickable. Essentially, it's a selec ...

Learn how to manipulate data within a MongoDB database schema using Node.js and Mongoose: inserting, saving, and updating records

When inserting data into the MongoDB schema presented below, make sure that Employee name, Project name, and client name can be the same, but the employee ID must be unique. Duplicate entries are not allowed. var StatusSchema = new mongoose.Schema({ ...

Is there a way to implement Bootstrap 5 toast in Vue.js and navigate to a different page, such as after submitting a form?

Is there a way to incorporate the bootstrap5 toast in vuejs while also redirecting to another page? For example, after submitting a form and being redirected to a new page, I would like a toast message to appear with the statement "Your form has been sub ...

Encountering a challenge with Nuxt where I am unable to navigate back when utilizing the require method

After successfully viewing the image, I encountered an error when trying to navigate back using <NuxtLink :to="{ path: 'About', hash: '#secondNav' }" class="close">, which resulted in a message stating Cannot f ...

Having trouble with the @keyup event not functioning properly in Vue?

I'm attempting to trigger a method when the enter key is pressed, but for some reason it's not working. Here's the code snippet: <template> <div> <button @click="callEvent" @keyup.enter="callEvent"> Click </button ...

In order to ensure proper alignment, adjust the width of the select element to match the width of the

Is there a way for the select element to adjust its width based on the length of the selected option? I want the default option value's width to be shorter, but once another option is selected, I'd like the select element to resize itself so that ...

Ways to collect email address or name from an email message

Suppose I send an email to someone with a link at the bottom. The text of the link might be something like click me. When the user clicks on this link, they will be directed to a webpage. On this webpage, a message saying "Thank you" will be displayed a ...

What steps can I take to ensure that the children of my dropdown menu do not trigger the focusout event of the dropdown itself?

It's frustrating how children inherit their parent's event listeners by default, even if they are added after the listener was created. This just seems counterintuitive to me. I only want to add a listener to the parent element, not to all of its ...

Traverse numerous arrays in JavaScript

I am attempting to search through three separate arrays of strings using Javascript. The goal is to find a user-inputted name and determine in which array it is located. Here is an example of what I am trying to achieve: HTML let users = ['mario&a ...

Managing HTML5 Video in a slider

I've designed a unique video slider that cycles through 4 videos. Each video has a custom play button and additional overlay content. Once the video starts playing, the overlay content and play button fade out to reveal the default video controls. The ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Nuxt.js is failing to recognize a custom plugin and is returning undefined

After spending time creating a custom plugin for a local database in Nuxt.js, I ran into an issue when trying to register it in nuxt.config.js. To troubleshoot, I tested the example code from the documentation and found that it didn't work either. Thi ...

Animating with jQuery to a specific offset or position

Currently, I am utilizing jQuery animate to modify the location of an element: $('#item').animate({'top' : '-50'}, 0); The goal is to set the position without any animations. I experimented with both offset and position, but ...

The jQuery .on event function is not compatible with a dynamic selector

I am facing a challenge in creating an onClick functionality for a dynamically loaded element with an ID stored in a variable called $element. The ID is in string format and I am trying to pass it to the event handler using the .on method like this: ... . ...

Having trouble with JQuery Ajax when trying to send multiple data at once?

name = "John Doe"; username = "johndoe123"; password = "secure123"; $.ajax({ type: 'POST', url: "https://example.com/api", data: { name: name, username: username, password: password }, success: function(response, status, xhr ...

An issue arose upon restarting my Eclipse software

Upon restarting my Eclipse, I encountered the following error message: "Plug-in com.android.ide.eclipse.adt was unable to load class com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor." As a beginner, could you advise me on how to addres ...