如何在Vue中异步加载vuetify下拉菜单(v-select)

时间:2019-01-23 07:10:01

标签: typescript vuejs2 vuetify.js

我有一个问题,需要异步获取v-select Vuetify组件的数据。问题是v-select组件仅对Array属性的:items起作用。异步获取数据的解决方法是什么:

  

无效的道具:类型“道具”的类型检查失败。期望数组,得到   承诺

模板

<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 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"];
}

3 个答案:

答案 0 :(得分:0)

我发现最好的解决方案/解决方法是创建一个局部变量并返回该局部变量实例。我只是通过索引来为我的动态组件创建一个唯一的对象

模板

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

脚本

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];
}

因此v-select组件将监听局部变量。填充后,它将更新v-select项。

答案 1 :(得分:0)

另一种替代方法可能是使用asyncComputed,它是opensource project

data: {
    userId: 1
},
asyncComputed: {
 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"];
 }
}

答案 2 :(得分:0)

Thx @ Ruslan,asyncComputed效果很好。以下是我的代码的摘录“ GetClients”是我选择的计算源。

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() {