Vuejs绑定多个复选框1

时间:2018-10-28 10:59:02

标签: vue.js vuejs2 vuetify.js

每月如何绑定Quater?我尝试使用观察器进行操作,但随后必须搜索每个元素等

Codepen demo

<div id="app">
 <v-card>
<v-card-text class="grey lighten-3">
  <v-radio-group row class="mt-0" hide-details>
    <v-checkbox label="Q1" v-model="check_q1" hide-details class="mt-0"></v-checkbox>
    <v-checkbox label="Q2" v-model="check_q2" hide-details class="mt-0"></v-checkbox>
    <v-checkbox label="Q3" v-model="check_q3" hide-details class="mt-0"></v-checkbox>
    <v-checkbox label="Q4" v-model="check_q4" hide-details class="mt-0"></v-checkbox>
  </v-radio-group>
  <hr>
  <v-checkbox v-for="(month, index) in months" :key="index" hide-details class="mt-0" v-model="selected_months"  :label="month" :value="index"></v-checkbox>
</v-card-text>

1 个答案:

答案 0 :(得分:1)

有一种简单的解决方案是使用字典并在用户选中季度的复选框时监听change事件

methods: {
 toggleValue (value, quarter) {
      console.log(this.selected_months)
      var mapping = {
        'q1': [0, 1, 2],
        'q2': [3, 4, 5],
        'q3': [6, 7, 8],
        'q4': [9, 10, 11],
      }
      var months = mapping[quarter]
      if (!value) {
        this.selected_months = this.selected_months.filter(item => !months.includes(item))
      } else {
        this.selected_months = this.selected_months.concat(months)
        // make array unique
        this.selected_months = this.selected_months.filter((it, i, ar) => ar.indexOf(it) === i);
      }
      console.log(this.selected_months)
    }
}

和模板代码中的

  <v-radio-group row class="mt-0" hide-details>
    <v-checkbox label="Q1" v-model="check_q1" hide-details class="mt-0" @change="toggleValue($event, 'q1')"></v-checkbox>
    <v-checkbox label="Q2" v-model="check_q2" hide-details class="mt-0"
                @change="toggleValue($event, 'q2')"></v-checkbox>
    <v-checkbox label="Q3" v-model="check_q3" hide-details class="mt-0"
                @change="toggleValue($event, 'q3')"></v-checkbox>
    <v-checkbox label="Q4" v-model="check_q4" hide-details class="mt-0"
                @change="toggleValue($event, 'q4')"></v-checkbox>
  </v-radio-group>

您可以将映射更改为checbox的值:

var mapping = {
  'q1': ['January', 'February', 'March'],
  'q2': ['April', 'May', 'June'],
  'q3': ['July', 'August', 'September'],
  'q4': ['October', 'November', 'December'],
}

Codepen demo