這是個小功能,就是幾個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>
