vue中按鈕使用v-bind:class動態切換顏色(點擊A號button,背景色變化;點擊B號button,A號回覆原背景色,B變色)

當前Vue項目須要作一個按鈕切換的功能(點擊A號button,背景色變化;點擊B號button,A號回覆原背景色,B變色)html

  =====》  =====》vue

實現上述功能,最基礎的方法就是,動過獲取對應的dom,強制改變背景色:web

<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"; },

這種方式,雖然能實現功能,可是代碼臃腫,後期維護不便。dom

===============================================================ide

還有一種方法就是經過傳給 v-bind:class 一個對象,以動態地切換 classui

vue官方文檔this

<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>
相關文章
相關標籤/搜索