vue 实现单选/多选效果

本文探讨了如何在Vue中实现单选和多选效果。利用includes()方法进行元素判断,通过filter()方法过滤并处理数组元素,创建符合需求的新数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vue的多选效果
includes()方法判断是否包含某一元素,返回true或false表示是否包含元素,对NaN一样有效

filter()方法用于把Array的某些元素过滤掉,filter()把传入的函数依次作用于每个元素,然后根据返回值是true还是false决定保留还是丢弃该元素:生成新的数组

<template>
  <div class="content">
    <div ref="conCon">
      <p>标题一</p>
      <button @click="Change(index)" v-for="(item,index) in content1" :key="'info-'+ index" :class ="{'info':info,'active': classItem.includes(index)}" :value="item">{{item}}</button>
    </div>
    <div ref="conCon1">
      <p>标题二</p>
      <button @click="Change1(index)" v-for="(item,index) in content2" :key="'info1-'+ index" :class ="{'info':info,'active': classItem1.includes(index)}" :value="item">{{item}}</button>
    </div>
    <div style="margin-top: 10px;">
      <button @click="remove">一键清空</button>
      <div>当前选择的是:{{message}}</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'multiSelect',
  data () {
    return {
      content1: ['内容1', '内容2', '内容3', '内容4', '内容5', '内容6'],
      content2: ['选择1', '选择2', '选择3', '选择4', '选择5', '选择6'],
      message: [],
      info: true,
      classItem: [],
      classItem1:[]
    }
  },
  methods: {
    Change: function (index) {
      var Button = this.$refs.conCon.querySelectorAll('button')
      if (this.classItem.includes(index)) {
        this.classItem = this.classItem.filter(function (ele) {
          return ele !== index
        })
        this.message = this.message.filter(function(ele){
          return ele !== Button[index].value
        })
      } else {
        this.classItem.push(index)
        this.message.push(Button[index].value)
      }
    },
    Change1: function (index) {
      var Button1 = this.$refs.conCon1.querySelectorAll('button')
      if (this.classItem1.includes(index)) {
        this.classItem1 = this.classItem1.filter(function (ele) {
          return ele !== index
        })
        this.message = this.message.filter(function(ele){
          return ele !== Button1[index].value
        })
      } else {
        this.classItem1.push(index)
        this.message.push(Button1[index].value)
      }
    },
    remove: function (index) {
      this.classItem = []
      this.classItem1 = []
      this.message = []
    }
  }
}
</script>

<style scoped>
  button{
    width: 80px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background: #fff;
    outline: none;
    border: 0;
    border:1px solid #999;
    border-radius: 3px;
    cursor: pointer;
  }
  .active{
    border:1px solid red
  }
</style>
效果如下: 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值