首页 > 解决方案 > Vue级联自动完成对象键

问题描述

我尝试在 vue js 中进行 3 或 4 级级联自动完成。但它不能正常工作。这是 orjinal codepen

<div id="app">
  <v-app id="inspire">
    <v-card>
      <v-card-text>
        <v-layout wrap>
          <v-flex xs3 md3>
            <v-autocomplete v-model="category" :items="categories" label="Category"  full-width solo hint="Random set of categories">
            </v-autocomplete>
          </v-flex>
          <v-flex xs3 md3>
            <v-autocomplete v-model="purpose" :items="purposes" label="Purpose"  full-width solo hint="Based on the selected category">
            </v-autocomplete>
          </v-flex>
        </v-layout>
      </v-card-text>
    </v-card>
  </v-app>
</div>

js

new Vue({
  el: "#app",
  data() {
    return {
      model: null,
      product: null,
      category: null,
      purpose: null,
      categoriesPurposes: {
        "Farm Animals": ["cow", "sheep", "hen"],
        Directions: ["left", "right", "up", "down"],
        Time: ["past", "present", "future"],
        Element: ["air", "water", "tierra", "fire"]
      }
    };
  },
  computed: {
    categories() {
      return Object.keys(this.categoriesPurposes);
    },
    purposes() {
      if (!this.category) {
        return null;
      } else {
        return this.categoriesPurposes[this.category];
      }
    }
  }
});

我尝试了 1 个更深的级别,但第二个自动完成看起来对象。

我更改了数据,例如:

categoriesPurposes: {
        Asia:{
            "Farm Animals": ["cow", "sheep", "hen"],
            Directions: ["left", "right", "up", "down"],
            Time: ["past", "present", "future"],
            Element: ["air", "water", "tierra", "fire"]
          }
       }

但这次第二个自动完成数据似乎是对象

我如何访问密钥并显示它们?谢谢。

标签: javascriptvue.jsselectautocomplete

解决方案


你给了一个对象,它是 Vuetify 定义的非法值

[Vue warn]: Invalid prop: type check failed for prop 'items'. Expected Array, got Object

问题是你返回this.categoriesPurposes[this.category]的是一个对象而不是对象数组。为了能够传递对象数组,您需要查看 Vuetify 的规范。

链接到文档

这应该工作

      categoriesPurposes: {
        "Farm Animals": [
          {
            text: "This is the cow",
            value: "cow",
          },
          {
            text: "This is the sheep",
            value: "sheep",
          },
          {
            text: "This is the hen",
            value: "hen"
          }
        ],
        Directions: ["left", "right", "up", "down"],
        Time: ["past", "present", "future"],
        Element: ["air", "water", "tierra", "fire"]
      }

在这里做了一个工作示例


推荐阅读