想要动态控制元素的style属性最直接的就是使用v-bind 下面案例使用了另外的两种方法:
- ref绑定
- 直接操作DOM元素
<template>
<div id="app">
<div class="son" @click="change(0)" ref="lengends"></div>
<div class="son" @click="change(1)" ref="lengends"></div>
</div>
<!-- /#app -->
</template>
<script>
export default {
name: "About",
data(){
return{
lengend:{
color:['red','yellow'],
seen:[true,true]
}
}
},
mounted() {
let son=document.getElementsByClassName('son')
for (let i=0;i<son.length;i++){
son[i].style.backgroundColor=this.lengend.color[i]
}
},
methods:{
change(val){
this.lengend.seen[val]=!this.lengend.seen[val]
let son=document.getElementsByClassName('son')
son[val].style.backgroundColor=this.lengend.seen[val]?this.lengend.color[val]:'gray'
}
}
}
</script>
<style scoped>
.son {
height: 100px;
width: 100px;
margin: 20px;
}
</style>
点击效果图: ![请添加图片描述](https://img-blog.csdnimg.cn/3d49086a04de4a98aab9fd90c1b2a7a9.gif)
|