Vue - 样式绑定
实现功能:点击一次字体变颜色,再点一次字体恢复默认颜色
- 一. class 选择器的对象绑定
- 对象方式
- 数组方式
- 二. style 样式绑定
- 对象方式
- 数组方式
一. class 选择器的对象绑定
1. 对象方式
控制 class
选择器对象的是否展示来控制 css
样式
<template>
<div class="wrap">
<div @click="handleClickOne" :class="{activated:isActivated}">hello world</div>
</div>
</template>
<script>
export default {
data() {
return {
isActivated: false,
};
},
methods: {
handleClickOne() {
this.isActivated = !this.isActivated;
}
}
};
</script>
<style scoped>
.activated {
color: red;
}
</style>
2. 数组方式
可多个 class
对象,控制 class
对象值有无来控制 css
样式
<template>
<div class="wrap">
<div @click="handleClickTwo" :class="[activatedOne,activatedTwo]">hello world</div>
</div>
</template>
<script>
export default {
data() {
return {
activatedOne: "",
activatedTwo: "fontSize",
};
},
methods: {
handleClickTwo() {
// if (this.activatedOne == "fontColor") {
// this.activatedOne = "";
// } else {
// this.activatedOne = "fontColor";
// }
this.activatedOne = this.activatedOne == "fontColor" ? "" : "fontColor";
},
}
};
</script>
<style scoped>
.fontColor {
color: blue;
}
.fontSize {
font-size: 26px;
}
</style>
二. style 样式绑定
1. 对象方式
data
中数据作为 标签 的 css
样式
<template>
<div class="wrap">
<div @click="handleClickThree" :style="styleObj">hello world</div>
</div>
</template>
<script>
export default {
data() {
return {
styleObj: {
color: "green",
},
};
},
methods: {
handleClickThree() {
this.styleObj.color = this.styleObj.color == "green" ? "blue" : "green";
},
},
};
</script>
<style scoped>
</style>
2. 数组方式
可设置多个,data
中数据作为 标签 的 css
样式,也可 标签 中直接定义 css
样式
<template>
<div class="wrap">
<div @click="handleClickFour" :style="[fontColor,fontWeight,{fontSize:'22px'}]">hello world</div>
</div>
</template>
<script>
export default {
data() {
return {
fontColor: {
color: "#b035bf",
},
fontWeight: {
fontWeight: "bold",
},
};
},
methods: {
handleClickFour() {
this.fontColor.color =
this.fontColor.color == "#b035bf" ? "red" : "#b035bf";
},
},
};
</script>
<style scoped>
</style>
还没有评论,来说两句吧...