H_Franky 2020-11-25 22:10 采纳率: 22.7%
浏览 1159

vue,checkbox选中对应name存入数组,取消选中从数组中移除怎么写?

<template>
    <div class="select-box">
        <div @click="showOrHide">{{ chkNum }}{{ defaultUserNum }}</div>
        <transition name="checkboxselect">
            <div class="select-list" v-show="isCheckBoxShow">
                <label :for="item.value" v-for="(item, index) in usersTypes" :key="item.value">
                    <input type="checkbox" :id="item.value" @click="count(item.value, item.name, index)" ref="chkb" :name="item.name" />{{ item.name }}
                </label>
            </div>
        </transition>
    </div>
</template>
<script>
export default {
    name: "CheckBoxSelect",
    props: {
        // 选项
        usersTypes: {
            type: Array,
        },
        // 框中单位/内容
        defaultUserNum: {
            type: String,
        },
    },
    data() {
        return {
            isCheckBoxShow: false, // 下拉选项是否显示
            chkNum: 0, // 选中复选框数量
            selectedChkList: [], // 存放被选中的选项
        };
    },
    methods: {
        // 计算选中的checkbox数量和选中的项的value和name
        count(value, name, index) {
            var nums = 0;
            var chk = this.$refs.chkb;
            // console.log(chk);
            for (var i = 0; i < chk.length; i++) {
                if (chk[i].checked) {
                    nums++;
                }
            }
            this.chkNum = nums;
        },

        // 显示或隐藏选项框
        showOrHide() {
            this.isCheckBoxShow = !this.isCheckBoxShow;
        },
    },

代码和效果如上,这是子组件,想选中某一项就把它的name值存到数组selectedChkList中,取消选中则把这个name从数组中移除,然后把这个数组传递给父组件,这个怎么实现?求教,谢谢!

  • 写回答

4条回答 默认 最新

  • 快把钟哥带走 2020-11-26 07:35
    关注

    要求就是子组件给父组件传值,就通过`自定义事件`来实现。

    // 例如在父组件中,自定义事件v-on: child-tell-me, 事件名为'child-tell-me'
    <component-b v-on:child-tell-me='getMsg'></component-b>
    
    new Vue({
      // ...
      methods: {
          // 'child-tell-me'对应触发的方法,即父组件获取子组件传递的参数msg
          getMsg: function(msg){  
              console.log(msg)
          }
      }
    })
    // 在子组件中,添加一个事件触发,比如你点击之后,就触发父组件的自定义事件
    new Vue({
      // ...
      methods: {
        // 在sendMsg方法中,即触发'child-tell-me'方法,并传递参数
        sendMsg: function(msg){  
          this.$emit('child-tell-me', '你收到我发送的消息了吗?【componentB】')
        }
      }
    })
    评论

报告相同问题?

悬赏问题

  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决
  • ¥15 关于华为5g模块mh5000-31接线问题
  • ¥15 keil L6007U报错
  • ¥15 webapi 发布到iis后无法访问
  • ¥15 初学者如何快速上手学习stm32?
  • ¥15 如何自动更换布娃娃图片上的衣服
  • ¥15 心理学eprime编程
  • ¥15 arduino esp8266开发
  • ¥15 stm32单片机通过485发送命令给驱动器控制电机转动,同样的代码f103可以控制电机转动,换到f407不能动了,但是用串口助手调试407显示发送的命令都是正确的,卡了好久了这是发送规则