Vue - 样式绑定

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

一. 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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值