Vue - 样式绑定

た 入场券 2021-07-25 15:00 592阅读 0赞

实现功能:点击一次字体变颜色,再点一次字体恢复默认颜色

  • 一. class 选择器的对象绑定
        1. 对象方式
        1. 数组方式
  • 二. style 样式绑定
        1. 对象方式
        1. 数组方式

一. class 选择器的对象绑定

1. 对象方式

控制 class 选择器对象的是否展示来控制 css 样式

  1. <template>
  2. <div class="wrap">
  3. <div @click="handleClickOne" :class="{activated:isActivated}">hello world</div>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data() {
  9. return {
  10. isActivated: false,
  11. };
  12. },
  13. methods: {
  14. handleClickOne() {
  15. this.isActivated = !this.isActivated;
  16. }
  17. }
  18. };
  19. </script>
  20. <style scoped>
  21. .activated {
  22. color: red;
  23. }
  24. </style>

2. 数组方式

可多个 class 对象,控制 class 对象值有无来控制 css 样式

  1. <template>
  2. <div class="wrap">
  3. <div @click="handleClickTwo" :class="[activatedOne,activatedTwo]">hello world</div>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data() {
  9. return {
  10. activatedOne: "",
  11. activatedTwo: "fontSize",
  12. };
  13. },
  14. methods: {
  15. handleClickTwo() {
  16. // if (this.activatedOne == "fontColor") {
  17. // this.activatedOne = "";
  18. // } else {
  19. // this.activatedOne = "fontColor";
  20. // }
  21. this.activatedOne = this.activatedOne == "fontColor" ? "" : "fontColor";
  22. },
  23. }
  24. };
  25. </script>
  26. <style scoped>
  27. .fontColor {
  28. color: blue;
  29. }
  30. .fontSize {
  31. font-size: 26px;
  32. }
  33. </style>

二. style 样式绑定

1. 对象方式

data 中数据作为 标签css 样式

  1. <template>
  2. <div class="wrap">
  3. <div @click="handleClickThree" :style="styleObj">hello world</div>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data() {
  9. return {
  10. styleObj: {
  11. color: "green",
  12. },
  13. };
  14. },
  15. methods: {
  16. handleClickThree() {
  17. this.styleObj.color = this.styleObj.color == "green" ? "blue" : "green";
  18. },
  19. },
  20. };
  21. </script>
  22. <style scoped>
  23. </style>

2. 数组方式

可设置多个,data 中数据作为 标签css 样式,也可 标签 中直接定义 css 样式

  1. <template>
  2. <div class="wrap">
  3. <div @click="handleClickFour" :style="[fontColor,fontWeight,{fontSize:'22px'}]">hello world</div>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data() {
  9. return {
  10. fontColor: {
  11. color: "#b035bf",
  12. },
  13. fontWeight: {
  14. fontWeight: "bold",
  15. },
  16. };
  17. },
  18. methods: {
  19. handleClickFour() {
  20. this.fontColor.color =
  21. this.fontColor.color == "#b035bf" ? "red" : "#b035bf";
  22. },
  23. },
  24. };
  25. </script>
  26. <style scoped>
  27. </style>

发表评论

表情:
评论列表 (有 0 条评论,592人围观)

还没有评论,来说两句吧...

相关阅读

    相关 vue样式

    3.1、绑定class 绑定class样式--字符串写法,适用于:样式的类名不确定,需要动态指定 <div class="basic" :class="mood"

    相关 VUE 样式

    操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是属性,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接