style:
<style lang="scss">
button {
width: 80px;
height: 30px;
background-color: yellowgreen;
border: 0px;
color: #fff;
margin-left: 20px;
border-radius: 5px;
cursor: pointer;
}
.changeBtn {
background-color: cornflowerblue;
color: #000;
}
</style>
通过控制数据内的布尔值
html:
<div id="app">
<div>
<template v-for="btn,index in btnVal">
<button @click="change(index)" :class="{ 'changeBtn' : btn.isboom }">
{{ btn.name }}
</button>
</template>
</div>
</div>
js:
var vm = new Vue({
el: "#app",
data: {
btnVal: [
{ name: "按钮", isboom: false },
{ name: "按钮1", isboom: false },
{ name: "按钮2", isboom: false },
{ name: "按钮3", isboom: false }
]
},
methods: {
change(index) {
this.antherChange();
this.btnVal[index].isboom = ! this.btnVal[index].isboom; //点谁谁改变
// console.log(this.changeColor(this.btnVal)) //获取到为布尔值为真的按钮
},
changeColor(val) { //获取到点的东西
return val.filter((element)=>{
if(element.isboom){
return element;
}
})
},
antherChange(){ //点谁谁改变
this.btnVal.forEach(element => {
element.isboom=false
});
}
}
});
通过定义一个值去匹配 :class 中的布尔值
html:
<div id="app1">
<div >
<template v-for="btn,index in btnVal">
<button @click="changeBtn(index)" :class="{'changeBtn': index === number}">{{btn}}</button>
</template>
</div>
{{msg}}
</div>
js:
new Vue({
el:"#app1",
data:{
btnVal:["按钮一","按钮二","按钮三","按钮四","按钮五"],
number:null,
msg:null
},
methods: {
changeBtn(index){
this.number=index; //关键点!!!
}
},
})
改变按钮内的值和样式
<div id="app2">
<button @click="isTrue=!isTrue" v-if="!isTrue" >{{msg}}</button>
<button @click="isTrue=!isTrue" v-else :class="{'changeBtn': isTrue}">{{msg1}}</button>
</div>
<script>
new Vue({
el:"#app2",
data:{
msg:"危险操作",
msg1:"安全操作",
isTrue:true
},
})
</script>
方法二推荐!
<div id="app3">
<button @click="changeBtn" :class="{'changeBtn':isTrue}">{{msg}}按钮</button>
</div>
<script>
new Vue({
el:"#app3",
data:{
msg:"hihi",
isTrue:true
},
methods: {
changeBtn(){
this.isTrue=!this.isTrue;
if(this.isTrue){
this.msg="hihi"
}else{
this.msg="haha"
}
}
},
})
</script>