首页 > 解决方案 > 如何在 Vuejs 中显示选中的复选框值?

问题描述

参考链接https://jsfiddle.net/8xom729c/

<div class="checkbox-alignment-form-filter">
  <input type="checkbox" id="HR 3502 : 2004" class="vh-product" value="HR 3502 : 2004" v-model="checkboxestwo[0]" v-on:click="checkAlltwo()" />
  <label class="productlist-specific" for="HR 3502 : 2004">HR 3502 : 2004</label
                >
              </div>
              <div class="checkbox-alignment-form-filter7">
                <input
                  type="checkbox"
                  id="E250A2"
                  class="vh-product"
                   v-model="checkboxestwo[1]"
                  value="E250A"
                />
                <label class="productlist-specific" for="E250A2">E250A</label>
</div>

如何打印选定的复选框值,我的意思是当我单击任何复选框值时,我需要显示选定的值。

在 vuejs 中有没有其他方法可以做到这一点。

任何人都可以请提供一些意见。谢谢

标签: javascriptvue.js

解决方案


尽管正在使用,但v-model您可以使用 click 事件作为下面的代码@click="checkedInput。但优雅的解决方案是使用v-model.If 您在选择复选框之前需要额外的过滤。您可以使用这种类型的点击事件

let vue = new Vue({
  el: '#app',
  data: {
    checkedNames: [],
    checkedName: true,
    close: false
  },
  methods: {
    uncheck: function(checkedName) {
      this.checkedNames = this.checkedNames.filter(name => name !== checkedName);
      this.$refs[checkedName.toLowerCase()].checked = false
    },
    uncheckall: function(event) {
      this.checkedNames.forEach(e => this.$refs[e.toLowerCase()].checked = false)
      this.checkedNames = [];
    },
    mouseOver: function() {
      this.close = true;

    },
    mouseOut: function() {
      this.close = false;
    },
    checkedInput(event) {
      if (this.checkedNames.includes(event.target.value)) {
        this.uncheck(event.target.value)
      } else {
        this.checkedNames.push(event.target.value)
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<div id='app'>
  <ul class="checkboxes">
    <li><input type="checkbox" ref="jack" value="Jack" @click="checkedInput">
      <label for="jack">Jack</label></li>

    <li><input type="checkbox" ref="john" value="John" @click="checkedInput">
      <label for="john">John</label></li>

    <li><input type="checkbox" ref="mike" value="Mike" @click="checkedInput">
      <label for="mike">Mike</label></li>
  </ul>
  <br/>
  <ul class="tags">
    <li @mouseover="mouseOver" @mouseleave="mouseOut" @click="uncheck(checkedName)" class="badge badge-pill badge-primary" v-for="checkedName in checkedNames">
      {{ checkedName }}<span v-show="close" aria-hidden="true">&times;</span>
    </li>
    <li class="badge badge-pill badge-danger" @mouseover="mouseOver" @mouseleave="mouseOut" @click="uncheckall" v-show="checkedNames != ''">Clear</li>
  </ul>
</div>


推荐阅读