这是个小功能,就是几个span标签,点击让其切换颜色,但是使用中也有一些坑
(1)为了保存一组span标签的点击状态,我们使用数组arr保存,然后通过事件传递下标过来,this.arr[num] = ! this.arr[num],发现这样写其实不生效,为什么呢
其实,这是因为数组作为引用类型,我们通过下标去修改其值的话vue并不能动态的检测到,所以数据是改变了,但DOM却没有渲染,如果需要使vue能感知到,我们需要
使用vue指定的一些数组变更方法:pop,push,shift,unshift,splice,sort,reverse。


<template>
<div>
<p>11111111111111</p>
<!-- <p>
<span :style="{backgroundColor:this.flag1? 'red':''}" @click="fun(1)">第一个</span>
<span :style="{backgroundColor:this.flag2? 'red':''}" @click="fun(2)">第二个</span>
<span :style="{backgroundColor:this.flag3? 'red':''}" @click="fun(3)">第三个</span>
<span :style="{backgroundColor:this.flag4? 'red':''}" @click="fun(4)">第四个</span>
</p> -->
<p>
<span :style="{backgroundColor:this.arr[0]? 'red':''}" @click="fun(0)">第一个</span>
<span :style="{backgroundColor:this.arr[1]? 'red':''}" @click="fun(1)">第二个</span>
<span :style="{backgroundColor:this.arr[2]? 'red':''}" @click="fun(2)">第三个</span>
<span :style="{backgroundColor:this.arr[3]? 'red':''}" @click="fun(3)">第四个</span>
</p>
</div>
</template>
<script>
export default {
data() {
return {
flag1:false,
flag2:false,
flag3:false,
flag4:false,
arr:[false,false,false,false]
}
},
methods: {
fun(num){
console.log(num)
let status = !this.arr[num]
this.arr.splice(num,1,status)
// switch(num){
// case 1:
// this.flag1=!this.flag1
// break
// case 2:
// this.flag2=!this.flag2
// break
// case 3:
// this.flag3=!this.flag3
// break
// case 4:
// this.flag4=!this.flag4
// break
// }
}
},
}
</script>
<style scoped>
</style>
