vue-select允许重复

时间:2019-08-12 19:06:40

标签: javascript vue.js vue-select

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

选项:

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

1 个答案:

答案 0 :(得分: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>