v-autocomplete no selected option

Within my Vue.js 2 and Vuetify component, I am receiving the following data :

[ { "anio": 2022, "__typename": "Grupo" }, { "anio": 2020, "__typename": "Grupo" }, { "anio": 2018, "__typename": "Grupo" }, { "anio": 2017, "__typename": "Grupo" }, { "anio": 2016, "__typename": "Grupo" }, { "anio": 2015, "__typename": "Grupo" }, { "anio": 2014, "__typename": "Grupo" } ]

This array of objects is used in the :items property for the v-autocomplete.

<v-autocomplete
                    v-model="anyo"
                    :items="listAnyos"

However, my issue lies in the fact that I require the option with a selected v-model containing: 2023, but it does not select this option.

This data is retrieved from a graphql query and sent to another component. While all the data is present in listAnyos, if the graphql query is empty, I need to set the anyo as the current year in the v-autocomplete

UPDATE

In response, I adjusted my code as follows:

<v-autocomplete
                    label="Select Year"
                    :items="filteredYears"
                    item-text="anio"
                    item-value="anio"
                    v-model="selectedYear"
                    ></v-autocomplete>

And in my methods:

calcularAnio() {
                let anioActual =  new Date().getFullYear();
                let previousYear = anioActual.value - 1;
                this.years.filter((year) => year.anio === anioActual.value || year.anio === previousYear.value)
            }

I created a function and replaced anonymous functions with values stored in variables and years in props. However, the function does not run nor show any errors.

UPDATE 2

In my parent component:

<BarraBusqueda
                    :listAnyos="listaAnyos"
                    :listNumLiquidaciones="listaNumLiquidaciones"
                    :cargandoAnyos="cargandoAnyos"
                    :cargandoRegistros="cargandoRegistros"
                    :filtros="filtros"
                    :fechaGas="fechaGas"
                    @buscar="leerRegistros"
                    v-if="fechaGas"
                />

Upon API response, the previous array is returned. In my child component's mounted function, I included this code:

const currYear = new Date().getFullYear();

if (!this.selectedYear) {
  this.listAnyos.unshift({
     "anio": currYear,
     "__typename": "Grupo"
  })

   this.items = this.listAnyos;

}

Now, my v-autocomplete looks like this:

<v-autocomplete
                    label="Ejercicio"
                    outline
                    v-model="selectedYear"
                    :items="items"
                    item-text="anio"
                    item-value="anio"
                    menu-props="offsetY"
                    :loading="cargandoAnyos"
                    :error-messages="anyoErrores"
                    :readonly="cargandoRegistros"
                />

Unfortunately, only the current year is displayed, not all the years, and the current year is not selected.

Thank you for reading and apologizes for any language barriers.

Answer №1

According to my understanding, your goal is to automatically assign the current year in the autocomplete field and set it as the default value if the value of selectedYear is not received correctly from the backend or API call.

If this is what you're looking for, here's a functional demo :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    listAnyos: [{
      "anio": 2022,
      "__typename": "Grupo"
    }, {
      "anio": 2020,
      "__typename": "Grupo"
    }, {
      "anio": 2018,
      "__typename": "Grupo"
    }, {
      "anio": 2017,
      "__typename": "Grupo"
    }, {
      "anio": 2016,
      "__typename": "Grupo"
    }, {
      "anio": 2015,
      "__typename": "Grupo"
    }, {
      "anio": 2014,
      "__typename": "Grupo"
    }],
    selectedYear: null,
  }),
  mounted() {
    const currYear = new Date().getFullYear(); 
    // If the 'selectedYear' is null from the backend or API, just assign the current year ('currYear') to the autocomplete and set it as the selected value.
    if (!this.selectedYear) {
      this.listAnyos.unshift({
        "anio": currYear,
        "__typename": "Grupo"
      })
    }
    this.selectedYear = currYear
  }
})
<script src="https://unpkg.com/babel-polyfill/dist/polyfill.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef999a8aafddc197">[email protected]</a>/dist/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c4c7d7c6dbd4cbf2809c859c83">[email protected]</a>/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c2a293928353a251c6e726b726d">[email protected]</a>/dist/vuetify.min.css"/>
<div id="app">
  <v-app id="inspire">
      <v-container fluid>
        <v-row
          align="center"
        >
          <v-col cols="12">
            <v-autocomplete
              v-model="selectedYear"
              :items="listAnyos"
              item-text="anio"
              item-value="anio"
            ></v-autocomplete>
          </v-col>
        </v-row>
      </v-container>
  </v-app>
</div>

Answer №2

import { computed } from "react";

 const years = [
      { year: 2022, __typename: "Group" },
      { year: 2020, __typename: "Group" },
      { year: 2018, __typename: "Group" },
      { year: 2017, __typename: "Group" },
      { year: 2016, __typename: "Group" },
      { year: 2015, __typename: "Group" },
      { year: 2014, __typename: "Group" },
    ];

    const currentYear = computed(() => new Date().getFullYear());
    const previousYear = computed(() => currentYear.value - 1);

    const filteredYears = computed(() =>
      years.filter((year) => year.year === currentYear.value || year.year === previousYear.value)
    );
   <div>
    <v-select
      label="Select Year"
      :items="filteredYears"
      item-text="year"
      item-value="year"
      v-model="selectedYear"
    ></v-select>
  </div>

Please give it a try and see if it functions correctly. Fetching the current year (2023) using JavaScript.

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

How to extract query string parameters using node.js

I'm currently working on fetching query string parameters from a URL using the node.js restify module. This is an example of the URL I am dealing with: Here is the relevant code snippet: server.use(restify.bodyParser()); server.listen(7779, functi ...

Top Strategies for PHP - Managing Directs and Header Content

PHP is a versatile language frequently used for generating 'templates' like headers to maintain a consistent look across websites and simplify updates via require or include commands. Another common task involves managing log-ins and redirecting ...

Encountering an issue with undefined property 'path' while attempting to upload an image on the frontend in React

I have encountered an issue while trying to upload an image on the frontend. The error message displayed is: message: "Cannot read property 'path' of undefined" status: "fail" When I log req.file on the backend and attempt to ...

What is the best way to organize objects by their respective dates?

I am retrieving data from a database and I would like to organize the response by date. I need some assistance in grouping my data by date. Below is an example of the object I have: var DATA = [{ "foodId": "59031fdcd78c55b7ffda17fc", "qty" ...

What is the process for computing two input values and placing the outcome in a different input field using Vue.js?

Check out my input fields below: <input v-model="form.sale_quantity" @change="computed" type="number" class="form-control" name="sale_quantity" id="sale_quantity" placeholder="Quantity&quo ...

The Vuetify Navigation Drawer functions correctly initially but then suddenly halts

When utilizing a Vuetify navigation drawer, I encountered an issue with the element that triggers its opening. The trigger element, v-toolbar-side-icon, is located in a separate component within the header section. To manage the open/close state of the dra ...

How can you retrieve the keys of an object that conforms to an interface?

In the following demonstration, we have two objects - KEYS and KEYS2. When importing KEYS in index.ts, autocomplete suggestions are available for K1 and K2 because KEYS does not adhere to an interface. On the other hand, with KEYS2, autocomplete is not pr ...

What is the solution to the error "Maximum update depth exceeded. Calls to setState inside componentWillUpdate or componentDidUpdate" in React?

Everything was running smoothly until this unexpected issue appeared. I attempted to change the condition to componentDidMount, but unfortunately, that didn't resolve the problem. The error is occurring in this particular function. componentDidUpd ...

Opting for fetch over jQuery's ajax for making successful GET requests to an API

Recently, I found myself in a situation where I needed to convert a function that uses a remote API from returning a callback to returning a Promise. This change presented an opportunity for me to also switch from using $.ajax to fetch, since fetch already ...

Trouble with Bootstrap v4 toggle drop-down menu functionality detected in local environment, yet functions correctly when live on the

Today, I've encountered an issue with my Bootstrap v4 collapsible hamburger menu on my local XAMPP server. Interestingly, the menu works perfectly fine on my public website when the display is 768px wide in Chrome and Firefox. I have searched through ...

Tips for accessing a web service using JavaScript (AJAX)

I have two projects: one is a web service and the other is an ASP.NET web project. I am trying to insert data using JSON (with AJAX). I tested the web service file with code behind and it works fine, but I'm encountering an error with the JavaScript ...

Script in Javascript halting Internet Explorer's operation

I'm encountering a problem with Internet Explorer freezing due to the following code. This code is part of a project that focuses on handling student grades: var array1 = StudentGradeAreadHugeList(); var nextArrayItem = function() { var grade = ...

The themes showcased in the Bespoke.js documentation and demo exhibit unique designs

Recently, I stumbled upon an incredible HTML5 framework for presentations. For more information, you can check out the documentation here. You can also view a demo of the framework by visiting this link. However, I was disappointed to find that the caro ...

Repetitive series of HTTP requests within a looping structure

Within my AngularJS project, I encounter the need to execute a varying number of HTTP requests in sequence. To achieve this, I believe that utilizing a loop is necessary: for (let i = 0; i < $scope.entities.length; i++) { MyService.createFixedValue ...

Trigger a Vuex action from a component once a mutation has finished

I am facing a situation with my Vue component where I need to call a Vuex action in the create hook. This action, an api.get request, fetches data and then dispatches a mutation. Once this mutation is completed, I have to trigger an action in another store ...

Boundaries on Maps: A guide to verifying addresses within a boundary

User provides address on the website. If the address falls within the defined boundary, it is marked as "Eligible". If outside the boundary, labeled as "Ineligible". Are there any existing widgets or code snippets available to achieve this functio ...

Is there a more efficient approach to displaying a list of elements and sharing state in React with TypeScript?

Check out this code sample I'm attempting to display a list with multiple elements and incorporate a counter on the main element that updates every time one of the buttons is clicked. I'm uncertain if this approach is optimal, as I am transition ...

I am currently experiencing difficulties with loading files in Magento even though they are present on the server

I am experiencing difficulties with a Magento 1.5.1 installation that was not a fresh setup, but rather one that was transferred to another server (files and database copied over). The issue I am facing is related to the failure of my Javascript files to ...

Exploring the best practices for rendering nested array elements in React.js

Is there a way to display only one URL from a nested array in React using CardMedia component? https://i.sstatic.net/K6JDz.png {props.currentTodos.map((currentTodo) => ( <CardMedia className={cl ...

Create JavaScript variable from either HTML or database sources

Hello, I am trying to implement a counter that retrieves its value from a JavaScript file, but I would like to customize it. Below is the JavaScript code: function updateCounter(count) { var divisor = 100; var speed = Math.ceil(count / divisor); ...