Tips for asynchronously loading items in a v-select dropdown of Vuetify within a Vue application

I am facing an issue with asynchronously fetching data for the v-select Vuetify Component. The problem is that the v-select component only accepts an Array for the :items attribute. Is there a workaround to fetch data asynchronously?

Error: Invalid prop type - expected Array, received Promise

template:

<template>
    <v-layout row wrap>
        <v-flex xs12 md6 v-for="(field, index) in fields" :key="index" v-show="!field.hidden">
            <v-text-field v-if="field.component === 'v-text-field'" :label="field.label"></v-text-field>
            <v-select
                v-else-if="field.component === 'v-select' "
                :label="field.label"
                :items="(typeof field.items === 'string') ? getLookups(field.items) : []"
            ></v-select>
            <v-checkbox v-else-if="field.component === 'v-checkbox'" :label="field.label"></v-checkbox>
        </v-flex>
    </v-layout>
</template>

async method:

async getLookups( api: string | string[]) {
    // Mock Async timeout
    var wait = (ms: any) => new Promise((r, j) => setTimeout(r, ms));
    wait(2000);
    return ["test1", "test2", "test3", "test4"];
}

Answer №1

I discovered a great solution by creating a local variable and returning the instance of that variable. By passing through the index, I was able to create a unique object for my dynamic component.

template:

<template>
    <v-layout row wrap>
        <v-flex xs12 md6 v-for="(field, index) in fields" :key="index" v-show="!field.hidden">
            <v-text-field v-if="field.component === 'v-text-field'" :label="field.label"></v-text-field>
            <v-select
                v-else-if="field.component === 'v-select' "
                :label="field.label"
                :items="(typeof field.items === 'string') ? getLookups(index, field.items) : field.items"
            ></v-select>
            <v-checkbox v-else-if="field.component === 'v-checkbox'" :label="field.label"></v-checkbox>
        </v-flex>
    </v-layout>
</template>

script:

private lookups: any = {};

getLookups(index: number, api: string | string[]) {
    // Mock Async timeout
    var wait = (ms: any) => new Promise((r, j) => setTimeout(r, ms));
    wait(2000).then(() => {
        this.lookups[index] = ["test1", "test2", "test3", "test4"];
    });
    return this.lookups[index];
}

Therefore, the v-select component will be constantly checking the local variable. Once it is populated, it will update the items displayed in the v-select.

Answer №2

Another option could involve implementing the asyncComputed feature, which is provided by an interesting open-source project.

data: {
    userId: 1
},
asyncComputed: {
 async getLookups( api: string | string[]) {
   // Simulating an Asynchronous timeout
  var wait = (ms: any) => new Promise((r, j) => setTimeout(r, ms));
  wait(2000);
  return ["test1", "test2", "test3", "test4"];
 }
}

Answer №3

Hey @Ruslan, wanted to give you a shoutout for introducing me to asyncComputed - it's been a game changer for me. I've included a snippet from my code where "GetClients" serves as the computed source for my select options.

async created() {
    if (this.id) {
      this.action = "Update";
      this.getItem();
    }
  },
  asyncComputed:{
    async getClients(){
      const items = await API.graphql({
        query: listClients
      });
      return items.data.listClients.items;
    }
  },
  methods: {
    async getItem() {

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

Issues persist with the Vue model not being updated

Whenever I attempt to update the model data of my custom text-area component this.message='<span id="foo">bar</span>, the text and html do not appear in the htmltextarea tag as expected. However, I can see the update being applie ...

How can I add .htaccess to Vue production when using npm run build?

While using Vue CLI 3 and vue-router with history mode, I encountered this particular issue. Upon further investigation, I discovered that inserting a .htaccess file inside the dist folder after running npm run build resolved the issue. Is there a way to ...

Navigating through Expo with Router v3 tabs, incorporating stack navigation, search functionality, and showcasing prominent titles

I've been working on designing a navigation header similar to the Apple Contacts app, with a large title and search function, but only for the Home Screen. All other tabs should have their own unique settings, like different titles or hidden navigatio ...

The hierarchy of precedence when using the TypeScript Type Assertion operator

Is it necessary to wrap the js-ternary operator with 'as' Type Assertion? ios ? TouchableOpacity : View as React.ElementType Will it automatically use the result of '?:' since it comes first? Or would a better implementation be: (ios ...

Verify the completeness of data types within an array in typescript

I am currently developing a comprehensive match function that I want to ensure is exhaustive during compile time. Although adding a default case would help with this, I am intrigued by some interesting dependent typing techniques I have come across. It wou ...

Declaring TypeScript functions with variable numbers of parameters

Is it possible to define a custom type called OnClick that can accept multiple types as arguments? How can I implement this feature so that I can use parameters of different data types? type OnClick<..> = (..) => void; // example usage: const o ...

Why isn't my component calling the service.ts file?

In my Angular project, I am working on a home component that contains a specific method. This method is defined in a service file called service.ts and imported into the homecomponent.ts file. The method is named filterClicked with a condition within the s ...

In Typescript, inheritance of classes with differing constructor signatures is not permitted

While working on implementing a commandBus, I encountered an issue when trying to register command types with command handlers for mapping incoming commands. My approach was to use register(handler : typeof Handler, command : typeof Command), but it result ...

Understanding and parsing JSON with object pointers

Is it possible to deserialize a JSON in typescript that contains references to objects already existing within it? For instance, consider a scenario where there is a grandparent "Papa" connected to two parents "Dad" and "Mom", who have two children togeth ...

Angular6 Observables used in API service with dynamic arguments

In order to achieve the desired behavior, I am trying to implement a system where when a user selects a label from a dropdown menu, an API call is made with that specific label as an argument. Subsequently, a chart should be redrawn using the data received ...

In the d.ts file, Typescript simply creates the line "export {};"

After executing the tsc command to compile my project into the dist directory, I noticed that typescript is generating an incorrect or empty d.ts file. Here is a snippet of my tsconfig.json: { "compilerOptions": { "module": " ...

Sharing methods between two components on the same page in Angular can greatly improve code efficiency

On a single page, I have two components sharing some methods and properties. How can I utilize a service to achieve this? See the sample code snippet below... @Component({ selector: 'app', template: '<h1>AppComponent1</h1>' ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

Integrating Typescript with React Redux-Thunk

Currently, I am attempting to type my Redux Actions using Redux Thunk Below is an example of one Action: export function logout() { return async(dispatch) => { try { const value = localStorage.removeItem("token"); dispatch(cons.upda ...

How to easily scroll to the top of the previous page in Angular 8

In my Angular 8 application, there are buttons that are meant to take the user back to the previous page when clicked. While the functionality works as expected, I am facing an issue where the page does not automatically scroll to the top upon navigating ...

The attribute 'subtle' is not found within the definition of 'webcrypto' type

Currently, I am working with Node v17.4 and I am looking to utilize the webcrypto API. Referencing this specific example, I am attempting to include subtle in my project, but TypeScript is throwing an error: Property 'subtle' does not exist on ...

Develop a web application in ASP.NET MVC 4 utilizing bundle configurations

At my workplace, we have an ASP.NET WebApp that utilizes ASP.NET MVC Bundles. To give you a clear picture, here is a snippet of the code: public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery ...

How can I obtain the rowIndex of an expanded row in Primeng?

<p-dataTable [value]="services" [paginator]="true" expandableRows="true" rowExpandMode="single"> ...</p-dataTable> There is a similar example below: <ng-template let-col let-period="rowData" let-ri="rowIndex" pTemplate="body">...</ ...

Retrieving the name of the current page in ionViewCanEnter

While working with Ionic 2, I am currently facing a challenge in identifying the name of the page that triggered the navigation (PUSHER) before entering the destination page (PUSHEE). Within the PUSHEE page, I have an ionViewCanEnter function where I need ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...