改变按钮颜色,并且不会影响其它按钮的颜色

本文介绍了一个Vue组件,展示了如何通过v-for指令动态渲染按钮列表,并通过点击事件改变按钮的状态,更新按钮样式。利用data和methods实现按钮的领取与已领取状态切换,同时展示了CSS样式在不同状态下的应用。

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

<!-- vue文件-->
<template>
	<view>
		<view v-for="(item,index) in loadBtnList">
			<button :class="item.btnStyle" type="default" style="margin: 20px;" @click="changeStyle(index)">{{item.title}}</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loadBtnList: [],
				idList: []
			}
		},
		mounted() {
			this.getBtnList()
			this.loadStyle()
		},
		methods: {
			changeStyle(index) {
				this.idList.push(this.loadBtnList[index].id)
				this.$set(this.loadBtnList,index,{...this.loadBtnList[index],showBtn: true})
				this.loadStyle()
			},
			getBtnList() {
				var a = [{id:1,name:'按钮1'},{id:2,name:'按钮2'},{id:3,name:'按钮3'},{id:4,name:'按钮4'}]
				this.loadBtnList = a
				this.loadBtnList.forEach(item=> {
					item.showBtn = false
					item.btnStyle = 'style1'
					item.title = '领取'
					
				})
			},
			loadStyle() {
				for(var i=0;i<this.loadBtnList.length; i++) {
					this.idList.forEach(item=> {
						if(item==this.loadBtnList[i].id) {
							this.$set(this.loadBtnList,i,{...this.loadBtnList[i],showBtn: true})
							if(this.loadBtnList[i].showBtn) {
								this.loadBtnList[i].btnStyle = 'style2'
								this.loadBtnList[i].title = '已领取'
							}
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.style1 {
		background: #00ff00;
	}
	.style2 {
		background: #ff0000;
	}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值