【问题标题】:Populate V-select from json从 json 填充 V-select
【发布时间】:2021-05-12 08:20:55
【问题描述】:

我在从后端收到的 JSON 中填充 v-select 时遇到问题。我是 vuetify 的新手,网上分享的一些解决方案让我很困惑。

这是我的 JSON

{
        "id": 2,
        "quantityOnHand": 7,
        "idealQuantity": 10,
        "product": {
            "id": 2,
            "createOn": "0001-01-01T00:00:00",
            "updateOn": "0001-01-01T00:00:00",
            "name": "10LB Dark Roast",
            "description": "10LB of Dark Roast Coffee Beans",
            "price": 67.0,
            "isTaxable": true,
            "isArchived": false
        }
    },
    {
        "id": 1,
        "quantityOnHand": 48,
        "idealQuantity": 10,
        "product": {
            "id": 1,
            "createOn": "0001-01-01T00:00:00",
            "updateOn": "0001-01-01T00:00:00",
            "name": "10LB Light Roast",
            "description": "10LB of Light Roast Coffee Beans",
            "price": 67.0,
            "isTaxable": true,
            "isArchived": false
        }
    },

这是我的 Vuejs 前端代码:

                    <template v-slot:[`item`]="{ inventory }">
                      <v-select
                        :items="inventory.product.name"
                        label="Product Receive"
                      ></v-select>
                    </template>

这是我正在使用的脚本(Typescript),可能与它有关。

  inventory: IProductInventory[] = [];

  async intialize() {
    this.inventory = await inventoryService.getInventory();
    await this.$store.dispatch("assignSnapshots");
  }
  async created() {
    await this.intialize();
  }

这是 IProductInventory 和 IProduct 的接口

export interface IProduct {
  id: number;
  createdOn: Date;
  updatedOn: Date;
  name: string;
  description: string;
  price: number;
  isTaxable: boolean;
  isArchived: boolean;
}

export interface IProductInventory {
  id: number;
  product: IProduct;
  quantityOnHand: number;
  idealQuantity: number;
}

【问题讨论】:

    标签: vue.js vuetify.js


    【解决方案1】:

    你应该通过items prop 传递你的数组:

    <v-select
      label="Product Receive"
      :items="inventoryItems">
    </v-select>
    

    对于inventoryItems,您可以使用计算属性:

    computed: {
      inventoryItems () {
        return yourArray?.map(inventory => ({
          text: inventory.product.name,
          value: inventory.product.id
        }))
      }
    }
    

    更多详情请见v-select API

    【讨论】:

    • 是拼写错误还是yourArray变量后面的问号有用?
    • 称为可选链developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。如果 yourArray 一开始是undefined,我会使用它来避免错误。
    • 谢谢,这就是我的想法,但找不到任何文档!
    • 它给了我一个错误。 “从不”类型上不存在属性“产品”。
    • @MuhdDanie 抱歉,我没有使用 TypeScript。我猜你可能需要声明类似yourArray?.map(inventory =&gt; &lt;IProduct&gt;{...})的类型。
    猜你喜欢
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2019-08-20
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多