0

我正在动态创建允许多项选择的 vue-select 下拉列表。但是这些下拉列表允许选择相同的选项。如何在不使用 v-model 的情况下更改此行为(因为我正在动态创建这些列表)?

选项:

 "categories": [
    {
      "id": 1,
      "name": "Math",
      "years": [
        { "id": 14, "name": "4" },
        { "id": 15, "name": "5" },
        { "id": 16, "name": "6" }
      ]
    },
    {
      "id": 2,
      "name": "Science",
      "years": [
        { "id": 11, "name": "1" },
        { "id": 12, "name": "2" },
        { "id": 13, "name": "3" }
      ]
    }
  ]

HTML:

  <div
    v-for="category in categories">
    <label>{{category.name}}</label>
    <vue-select
      :options="category.years"
      label="name"
      @input="onCategoryYearSelect"
      multiple>
    </vue-select>
  </div>
4

1 回答 1

1

首先,您应该定义数据属性,您将在其中存储您选择的年份。

它将是一个对象,其中的键将是类别 ID,值将是选定的年份。

然后你应该处理<vue-select> @input事件,将选定的年份设置为适当的类别。

Vue.component('vue-select', VueSelect.VueSelect)

new Vue({
  el: "#app",
  data() {
    return {
      "selectedYears": {},
      "categories": [{
          "id": 1,
          "name": "Math",
          "years": [{
              "id": 14,
              "name": "4"
            },
            {
              "id": 15,
              "name": "5"
            },
            {
              "id": 16,
              "name": "6"
            }
          ]
        },
        {
          "id": 2,
          "name": "Science",
          "years": [{
              "id": 11,
              "name": "1"
            },
            {
              "id": 12,
              "name": "2"
            },
            {
              "id": 13,
              "name": "3"
            }
          ]
        }
      ]
    }
  },
   methods: {
    inputHandler(id, e) {
      if (this.selectedYears[id] && this.selectedYears[id].find(item => item.id === e.id)) return;
      
      this.$set(this.selectedYears, id, e);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-select@latest"></script>
<link rel="stylesheet" href="https://unpkg.com/vue-select@latest/dist/vue-select.css">
<div id="app">
  <div>
    <div v-for="category in categories" :key="category.id">
      <label>{{ category.name }}</label>
      <vue-select :options="category.years" label="name" multiple @input="inputHandler(category.id, $event)">
      </vue-select>
    </div>
    <h1>{{ selectedYears }}</h1>
  </div>
</div>

于 2019-08-12T19:12:29.443 回答