当前Vue项目需要做一个按钮切换的功能(点击A号button,背景色变化;点击B号button,A号回复原背景色,B变色)
=====》
=====》
实现上述功能,最基础的方法就是,动过获取对应的dom,强制改变背景色:
<div class="button1" v-on:click="YGDWKGMJ()" ref="ygdwkgmj">开发投资</div> <div class="button2" v-on:click="XKGMJ()" ref="xkgmj">成交均价</div> <div class="button2" v-on:click="LMDJ()" ref="lmdj">销售面积</div> <div class="button2" v-on:click="CLZFCJMJ()" ref="clzfcjmj">库存监测</div>
YGDWKGMJ() { this.$refs.ygdwkgmj.style.backgroundColor = "#3657be"; this.$refs.xkgmj.style.backgroundColor = "#192e5b"; this.$refs.lmdj.style.backgroundColor = "#192e5b"; this.$refs.clzfcjmj.style.backgroundColor = "#192e5b"; },
这种方式,虽然能实现功能,但是代码臃肿,后期维护不便。
===============================================================
还有一种方法就是通过传给 v-bind:class
一个对象,以动态地切换 class
<li v-for="(list,index) in leftPart" class="aa" @click="leftChange(index)" :class="{ liBackground:changeLeftBackground == index}">{{list.name}}</li>
data() { return { leftPart: [ { name: "开发投资" }, { name: "成交均价" }, { name: "销售面积" }, { name: "库存监测" } ], changeLeftBackground: 0, }; },
methods: { leftChange(index) { this.changeLeftBackground = index; }, }
<style scoped> .liBackground { background: -webkit-gradient(linear, 0 0, 0 100%, from(#303fb2), to(#2f70d4)); } </style>