js-vue中多个按钮状态选中类似于复选框与单选框实现

1.vue中多个按钮状态选中类似于复选框

在Vue中处理多个按钮的选中状态切换,通常我们会利用Vue的响应式数据系统来追踪每个按钮的选中状态。

html

html 复制代码
<div id="app">  
  <button  
    v-for="button in buttons"  
    :key="button.id"  
    :class="{ active: button.isSelected }"  
    @click="toggleSelection(button.id)"  
  >  
    {{ button.text }}  
  </button>  
</div>

js

javascript 复制代码
new Vue({  
  el: '#app',  
  data: {  
    buttons: [  
      { id: 1, text: '按钮1', isSelected: false },  
      { id: 2, text: '按钮2', isSelected: false },  
      { id: 3, text: '按钮3', isSelected: false }  
    ]  
  },  
  methods: {  
    toggleSelection(id) {  
      // 找到并点击的按钮并切换其选中状态  
      this.buttons.forEach(button => {  
        if (button.id === id) {  
          button.isSelected = !button.isSelected;  
        }  
      });  
    }  
  }  
});

css

css 复制代码
new Vue({  
  el: '#app',  
  data: {  
    buttons: [  
      { id: 1, text: '按钮1', isSelected: false },  
      { id: 2, text: '按钮2', isSelected: false },  
      { id: 3, text: '按钮3', isSelected: false }  
    ]  
  },  
  methods: {  
    toggleSelection(id) {  
      // 找到并点击的按钮并切换其选中状态  
      this.buttons.forEach(button => {  
        if (button.id === id) {  
          button.isSelected = !button.isSelected;  
        }  
      });  
    }  
  }  
});

定义一个buttons数组 ,其中包含了每个按钮的idtext(按钮上显示的文本)和isSelected按钮的选中状态)。

使用v-for指令来遍历buttons数组,并为每个按钮绑定了一个点击事件处理器toggleSelection,该处理器接收按钮的id作为参数。当按钮被点击时,toggleSelection方法会根据id找到对应的按钮,并切换其isSelected属性的值

使用:class绑定来根据按钮的isSelected状态动态添加active类,以改变按钮的样式来表示其选中状态。

2.vue中多个按钮状态选中类似于单选框

实现类似单选框的功能,即在一组按钮中只能同时选中一个,你可以通过维护一个变量来记录当前选中的按钮的id,并在点击按钮时更新这个变量。然后,根据这个变量来设置每个按钮的选中状态。

html 复制代码
<div id="app">  
  <button  
    v-for="button in buttons"  
    :key="button.id"  
    :class="{ active: selectedButtonId === button.id }"  
    @click="selectButton(button.id)"  
  >  
    {{ button.text }}  
  </button>  
</div>  
  
<script>  
new Vue({  
  el: '#app',  
  data: {  
    buttons: [  
      { id: 1, text: '按钮1' },  
      { id: 2, text: '按钮2' },  
      { id: 3, text: '按钮3' }  
    ],  
    selectedButtonId: null // 用来记录当前选中的按钮的id  
  },  
  methods: {  
    selectButton(id) {  
      // 更新当前选中的按钮id  
      this.selectedButtonId = id;  
    }  
  }  
});  
</script>  
  
<style>  
.active {  
  background-color: blue;  
  color: white;  
}  
</style>

buttons数组包含了所有按钮的信息,而selectedButtonId变量用于跟踪当前选中的按钮的id。每个按钮都绑定了一个点击事件处理器selectButton,当按钮被点击时,该处理器会更新selectedButtonId的值为被点击按钮的id

相关推荐
大怪v3 小时前
AI抢饭?前端佬:我要验牌!
前端·人工智能·程序员
新酱爱学习3 小时前
字节外包一年,我的技术成长之路
前端·程序员·年终总结
小兵张健3 小时前
开源 playwright-pool 会话池来了
前端·javascript·github
IT_陈寒6 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
codingWhat6 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
Lee川6 小时前
深度拆解:基于面向对象思维的“就地编辑”组件全模块解析
javascript·架构
代码老中医7 小时前
2026年CSS彻底疯了:这6个新特性让我删掉了三分之一JS代码
前端
进击的尘埃7 小时前
Web Worker 与 OffscreenCanvas:把主线程从重活里解放出来
javascript
不会敲代码17 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
踩着两条虫7 小时前
VTJ.PRO 双向代码转换原理揭秘
前端·vue.js·人工智能