如何在Vue中的<option>循环内获取对象关系?

时间:2019-03-19 08:34:43

标签: vue.js

让我们转到问题的重点。我有一个selection组件,它看起来像这样:

<template>
  <div class="row">
    <div class="col-md-6">
      <div class="form-group">
        <label for="category_id">
          Product Category
        </label>

        <select
          name="category_id"
          id="category_id"
          :class="form.errors.has('category_id') ? 'form-control is-invalid' : 'form-control'"
          v-model="form.sharedState.category_id">

          <option value="" disabled hidden>Select Category</option>
          <option
            v-for="category in categories"
            :key="category.id"
            v-text="category.name"
            :value="category.id"
            @click="$emit('category-selected', category.sub_categories)">
          </option>

        </select>

        <small
          class="form-text text-danger"
          v-if="form.errors.has('category_id')"
          v-text="form.errors.get('category_id')"></small>

      </div>
    </div>
    <div class="col-md-6">
      <div
        class="form-group"
        v-if="revealSubCategory"
        @category-selected="show">

        <label for="category_id">
          Sub Category
        </label>

        <select
          name="sub_category_id"
          id="sub_category_id"
          :class="form.errors.has('sub_category_id') ? 'form-control is-invalid' : 'form-control'"
          v-model="form.sharedState.sub_category_id">

          <option value="" disabled hidden>Select Sub Category</option>

          <option
            v-for="subcategory in subcategories"
            :key="subcategory.id"
            v-text="subcategory.name"
            :value="subcategory.id">
          </option>

        </select>

        <small
          class="form-text text-danger"
          v-if="form.errors.has('category_id')"
          v-text="form.errors.get('category_id')"></small>

      </div>
    </div>
  </div>
</template>
<script>
import BaseCard from './BaseCard.vue';

export default {
  components: {
    BaseCard
  },
  data() {
    return {
      categories: [],
      revealSubCategory: false,
      subcategories: [],

      form: new Form({
        sharedState: product.data
      })
    }
  },
  mounted() {
    this.getCategories();
  },
  methods: {
    getCategories() {
      axios.get('categories')
        .then(({data}) => this.categories = data);
    },
    show(subcategories) {
      this.revealSubCategory = true;
      this.subcategories = subcategories
    }
  }
}
</script>

一旦用户选择了类别选项之一,就会显示select sub category输入(在第二列)。每个类别选项都与从API中提取的子类别相关。

如何获取子类别并显示输入?我已经在@change标签上尝试过select,但是由于子类对象不在循环中,因此无法传递子类对象。并且@click事件似乎在option标签中无效。

1 个答案:

答案 0 :(得分:1)

您可以观看第一个选择并更改子类别的v模型。

watch:{
  "form.sharedState.category_id": function (val) {
     // update subcategories here
 }