vue动态添加样式

发布于 2023-07-05  211 次阅读


  • 凡是有-的style属性名都要变成驼峰式,比如font-size要变成fontSize
  • 除了绑定值,其他的属性名的值要用引号括起来,比如backgroundColor:'#00a2ff'而不是 backgroundColor:#00a2ff

【对象】

  • html :style="{ color: activeColor, fontSize: fontSize + 'px' }"

  • html :style="{color:(index==0?conFontColor:'#000')}"

【数组】

  • html :style="[baseStyles, overridingStyles]"
  • html :style="[{color:(index==0?conFontColor:'#000')},{fontSize:'20px'}]"

【三目运算符】

  • html :style="{color:(index==0?conFontColor:'#000')}"
  • html :style="[{color:(index==0?conFontColor:'#000')},{fontSize:'20px'}]"

【多重值】

此时,浏览器会根据运行支持情况进行选择

  • html :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"

【绑定data对象】

  • html :style="styleObject"
data() {    return{      styleObject: {        color: 'red',        fontSize: '13px'      }      }}
JavaScript

vue动态添加class的几种方式

p1,p为类名

【对象】

对象的形式: 用花括号包裹起来,类名用引号,

第一个参数 类名, 第二个参数:boolean值

优点: 以对象的形式可以写多个,用逗号分开

  `html :class="{'p1' : true}"`  `html :class="{'p1' : false, 'p': true}"`
JavaScript

【数组】

   `html :class="['p1', 'p2']"`   `html :class="[{'p1':true}]"`   `html :class="[{'p1': false}, 'p2']"`
JavaScript

三元表达式

注意点:放在数组中,类名要用引号

  • html :class="[ 1 < 2 ? 'p1' : 'p' ]"

【返回方法】class中还可以传方法,在方法中返回类名

`html :class="setClass"` method: {  setclass () {        return 'p1';      }  } 
JavaScript

详见:juejin.cn/post/684490…

1.用:style的方式

HTML部分:

<!-- 注意此处的属性名,需用驼峰式而不能用连接符式 -->
<div :style="{marginTop: enterpriseTheme === 'qinglianxiyu' ? '0' : '260px'}"
     class="view-btn">
</div>

<!-- 使用数组的形式,传入多个对象;常用于自定义弹框,width和其他样式是分开传的情况 -->
<div :style="[{width: `${width}px`}, otherStyle]"
     class="view-btn">
</div>

<!-- 使用”与“的形式,区别于三元表达式 -->
<div :style="data.bold && 'fontWeight: bold'"
     class="view-btn">
</div>
HTML

2.用:class的方式

HTML部分:

<div :class="{ 'no-margin-top': enterpriseTheme === 'qinglian
     class="view-btn">
</div>
HTML

CSS部分:

// 此处"margin-top: 260px;"直接写在 class="view-btn" 中.no-margin-top {   margin-top: 0;}
CSS

(附: 添加多个类名的情况  参考文章:vue中动态添加class类名_gary的博客-CSDN博客_vue 动态类名(vue中动态添加class类名))

<!-- 第一种方式:对象的形式 -->
<div :class="{'first-class' : isFirstClass, 'second-class': !isFirstClass}">对象的形式</div>
<!-- 第二种方式:三元表达式 注意点:放在数组中,类名要用引号-->
<div :class="[ isFirstClass ? 'first-class' : 'second-class' ]">三元表示式</div>
<!-- 第三种方式: 数组的形式 -->
<div :class="[firstClassName, secondClassName]">数组的形式</div>
HTML

只会写bug的bugming