vue动态绑定样式
通过动态绑定style和控制css属性的值来实现
效果是这样的,点击按钮的时候给文本赋值上随机的颜色。
一个很简单的功能,主要用到了js的random函数,vue动态绑定样式。
<template><div><div :style="{color:color1}" style="font-size: 25px;">123qwe</div><el-button @click="changeCol">切换颜色</el-button></div>
</template>
<script setup>
import { ref } from 'vue';const getRandomColr=()=>{// 生成第一个 0 到 255 之间的随机整数let num1 = Math.floor(Math.random() * 256);// 生成第二个 0 到 255 之间的随机整数let num2 = Math.floor(Math.random() * 256);// 生成第三个 0 到 255 之间的随机整数let num3 = Math.floor(Math.random() * 256);// 将三个随机数用逗号连接成一个字符串return `rgb(${num1},${num2},${num3})`;
}
//声明初始值
let color1=ref();
// 首次赋值
color1.value=getRandomColr();
//点击按钮 随机赋值一个颜色
const changeCol=()=>{color1.value=getRandomColr();
}</script >
声明一个变量color1来存储rgb颜色的值,声明一个方法来随机生成rgb的值,使用random函数来控制rgb的值 (0-255)。
当需要动态绑定多个值的时候,使用逗号隔开
<div :style="{color:color1,backgroundColor:color2}" style="font-size: 25px;">123qwe</div>
const color2=ref('#eee')
灰色的背景色可以看到已经添加上去了 。
通过变量结合三元运算符来控制是否加载类名
<template><div><h2 :class="isFlag ?'h2Active' :''" @click="isFlag=!isFlag">通过变量来控制是否加载类名</h2></div>
</template><script setup>
import { ref } from 'vue';const isFlag=ref(false);
</script><style scoped>.h2Active{color: red;
}</style>
运行效果,点击文本的时候去修改isFlag的值 来控制h2Active类名是否加载
在演示一个
当isFlag值发生变化的时候,会给第二个h2 添加动画去隐藏显示h2
<template><div class="box"><h2 :class="isFlag ? 'h2Active' : ''" @click="isFlag = !isFlag">通过变量来控制是否加载类名</h2><h2 :class="isFlag ? 'demoAnimation' : 'demoAnimation2'">这是一段文本xxxxxxxxxx</h2></div>
</template><script setup>
import { ref } from 'vue';const isFlag = ref(false);
</script><style scoped>
.box {overflow: hidden;width: 500px;border: 1px solid;
}.h2Active {color: red;
}@keyframes hide {from {transform: translateX(0%);}to {transform: translateX(100%);}
}@keyframes show {from {transform: translateX(100%);}to {transform: translateX(0%);}
}.demoAnimation {animation: show linear 2s forwards;
}.demoAnimation2 {animation: hide linear 2s forwards;
}
</style>
end