Vue3 v-bind绑定css中的var变量实现动态样式
在日常的开发中,我们常常遇到这样的需求:点击一个button改变页面中某个元素的样式,在这样的场景中,我们可以使用v-bind绑定css中的var变量,来动态的切换元素的样式
一个小栗子,在setup语法糖环境下,点击一个button动态切换另一个元素的背景色
<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的背景色,代码如下:
<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>
<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>
原文地址:https://blog.csdn.net/jiaoyangdetian/article/details/137640496
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!