0


Vue 动态改变css样式的方法总结

在网页开发中,我们经常会遇到动态的改变某个元素样式的需求,在vue里如何实现呢?官网上其实写的很详细了,对象语法,数组语法等。我自己总结了在开发中,个人用的比较多的三种方式

1.class,三元表达式

根据三元表达式来动态的在两种样式间切换

:class="[occupation === '请选择' ? 'lh60' : 'lh61']"
css:
lh60:{color:blue;}lh61:{color:red;}

2.:style=“xxxxx”,这里xxx可以是个函数,也可以是个计算属性

《1》 <!--HTML部分 --><div class="square" :style="{'background-color':isChange?'blue':'red',
'color':isChange?'white':'black'}">测试</div>

isChange是一个变量

在这里插入图片描述
注意!CSS property 属性名可以用驼峰式 (camelCase) 或短横线分隔 (kebab-case,要用引号括起来) 所以以下同等效果,同时三目运算符后的字符串也能换成data中的数据。

<!--HTML部分 --><div class="square" :style="{backgroundColor:isChange?color_active:color_disactive,
color:isChange?textColor_active:textColor_disactive}">测试</div>

在这里插入图片描述
vscode截图

//date部分
data:{
   isChange:false,
   color_active:'blue',
   color_disactive:'red',
   textColor_active:'white',
   textColor_disactive:'black'}

这个是函数的形式

《2》  style="handleStyle(second)”
......
handleStyle(deg) {
    return { transform: "rotate(" + deg + "deg)" };},

计算属性:

:style=“imgStyle”
......

computed: {imgStyle(){return{
            padding: this.spacing + "px",
        };},
}

这两种方式很像,区别在于,使用方法的时候,视图刷新,函数就会重新计算一遍值。计算属性,会把以前的值缓存起来,没有变化,就不会计算,直接返回以前的值

标签: vue.js css 前端

本文转载自: https://blog.csdn.net/qq_34953053/article/details/130288722
版权归原作者 肖邦的交响乐 所有, 如有侵权,请联系我们删除。

“Vue 动态改变css样式的方法总结”的评论:

还没有评论