首页 > 解决方案 > 如何在Vue js中将复选框与芯片绑定(双向绑定)

问题描述

我是 Vue Js 的新手。问题在于从表单中选择下拉菜单,选项以 div 中的复选框形式出现,在选择复选框时,芯片应显示带有复选框标签。但此处复选框自动被选中并显示芯片,但选择后应该显示一个复选框芯片,关闭芯片复选框应该取消选择。这是预期的但不会发生。这是我的代码。请帮助。

   <template>
    <div id="app">
     <v-layout row wrap>
         <v-flex v-for="chip in chips" xs12 sm4 md4>
          <v-checkbox   :label="chip.name" v-model="chip.text"></v-checkbox>
          //  checkbox not working
          </v-flex>
        <div class="text-xs-center">
       <v-select
       :items="dataArr"
        v-model="sensorDM"
       label="Select"
      class="input-group--focused"
     item-value="text"
     v-change="call(sensorDM)"
       ></v-select>
       <v-chip
          v-for="tag in chips"
          :key="tag.id"
          v-model="tag.text"
          close
        >
        {{ tag.name }}
        </v-chip> 
        <br>
        </div>
      </div>
    </template>
    <script>
    import axios from 'axios'
    export default {
      name: 'Creation',
      data: () => ({
       chips: [{
          id: 1, text: 'Device 1', name: 'Device 1'
        }, {
          id: 2, text: 'Device2', name: 'Device 2'
        }],
        chip1: false,
        chip2: true,
        dataArr: []
      }),
      created () {
        let self = this
        axios.get('http://localhost:4000/api/devices')
    .then(function (response) {
     self.fData(response.data.result)
    })
      },
      methods: {
      fData: function (message) {
      let self = this  
      message.forEach(function (el, i) {
        self.dataArr.push(el.sDM.name)
      })
    },
        call (mes) {
          let self = this
          axios.get('http://localhost:4000/api/part1/Models/' + mes)
    .then(function (res) {
      self.resObj = res.data.response
      self.resObj.forEach(function (el, i) {
        el['text'] = el.name
        el['isOpen'] = 'false'
      })
      self.chips = self.resObj
    })
        },
        submit(){
             console('hjkh')
        }    
      }
    }

嗨,我已经编辑了代码并从 created() 添加了函数调用

标签: javascriptvue.jsvuejs2vue-component

解决方案


我猜你想这样做https://codepen.io/ittus/pen/VxGjgN

<div id="app">
   <v-flex v-for="chip in chips" :key="chip.id" xs12 sm4 md4>
      <v-checkbox :label="chip.name" v-model="chip.selected"></v-checkbox>
      <v-chip
         v-model="chip.selected"
         close>
         {{ chip.name }}
      </v-chip>
   </v-flex>
   <div class="text-xs-center">
   </div>
</div>

new Vue({
  el: '#app',
  data() {
    return {
      chips: [{
      id: 1, text: 'Device 1', name: 'Device 1', selected: false
    }, {
      id: 2, text: 'Device2', name: 'Device 2', selected: false
    }],
    chip1: false,
    chip2: true,
    }
  }
})

我添加了selected属性,因为默认情况下 v-checkbox 和 v-chip 值是布尔值。


推荐阅读