Vue3 v-bind绑定css中的var变量实现动态样式

在日常的开发中,我们常常遇到这样的需求:点击一个button改变页面中某个元素的样式,在这样的场景中,我们可以使用v-bind绑定css中的var变量,来动态的切换元素的样式

一个小栗子,在setup语法糖环境下,点击一个button动态切换另一个元素的背景色

javascript 复制代码
<template>
  <div class="box">
    <div class="intro">
      <div class="btxt" :style="{'--text-color':textColor}">使用v-bind绑定语法糖中的颜色常量的值给style中的变量</div>
    </div>
    <div class="intro">
      <div class="btn" @click="changeColor">点击button改变textColor的值,动态更新颜色的值</div>
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue'
const textColor = ref("blue");
const changeColor = () => {
  if (textColor.value === "blue") {
    textColor.value = "pink";
  } else {
    textColor.value = "blue"
  } 
  
};
</script>
<style scoped lang="less">
.box{
  display: flex;
  flex-direction: column;

  .intro{
    background-color: antiquewhite;
    margin: 10px;
    padding: 15px;

    .btn{
      display: inline-block;
      padding: 18px 35px 18px 35px;
    }
  }
}
.btxt{
  padding: 18px 35px 18px 35px;
  color: var(--text-color);
}
</style>

一个小栗子,在非setup语法糖的环境下使用v-bind绑定css中的var变量,实现当鼠标悬停在一个button上时配置button的伪类hover中的背景色,点击button后通过切换var变量对应的颜色值,动态切换button的背景色,代码如下:

javascript 复制代码
<template>
  <div class="box">
    <div class="btn" :style="{'--color-back':backColor}" @click="changeEvent">
      使用v-bind绑定非setup语法糖环境下的style值
    </div>
  </div>
</template>
<script>
export default{
  name:"ChangeButton",
  data(){
    return {
      backColor: "cadetblue"
    }
  },
  methods:{
    changeEvent(){
      let color = this.$data.backColor
      if (color === "cadetblue") {
        this.$data.backColor = "orange"
      } else {
        this.$data.backColor = "cadetblue"
      }
    }
  }
}
</script>
<style scoped lang="less">
.box{
  .btn{
    background-color: var(--color-back);
    display: inline-block;
    padding: 18px 35px 18px 35px;
    border-radius: 5px;
  }
}
.btn:hover{
  background-color: lightgrey;
}
.btn:active{
  animation: changeck 0.3s ease;
}
@keyframes changeck {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.95);
  }
  100% {
    transform: scale(1);
  }
}
</style>
javascript 复制代码
<template>
  <div class="box">
    <div class="intro">
      <change-button></change-button>
    </div>
  </div>
</template>
<script setup>
import ChangeButton from './components/index.vue'
</script>
<style scoped lang="less">
.box{
  display: flex;
  flex-direction: column;
}
</style>
相关推荐
兆子龙10 分钟前
TypeScript高级类型编程:从入门到精通
前端·后端
SuperEugene12 分钟前
Vue3 模板语法规范实战:v-if/v-for 不混用 + 表达式精简,避坑指南|Vue 组件与模板规范篇
开发语言·前端·javascript·vue.js·前端框架
IT_陈寒19 分钟前
Python开发者的效率革命:这5个技巧让你的代码提速50%!
前端·人工智能·后端
Luna-player19 分钟前
Vue 3 + Vue Router 的路由配置,简单示例
前端·javascript·vue.js
用户693717500138420 分钟前
不卷AI速度,我卷自己的从容——北京程序员手记
android·前端·人工智能
xiaotao13127 分钟前
03. 原子化 CSS 思想
前端·css·tailwind
敲代码的约德尔人31 分钟前
JavaScript 设计模式完全指南
javascript·设计模式
angerdream33 分钟前
最新版vue3+TypeScript开发入门到实战教程之Vue3详解props
javascript·vue.js
小小亮0139 分钟前
qiankun的面试题
前端