Vue进阶(姚无玖):动态样式设置

前端开发 2023-09-13 12:04:28
118阅读

(文章列表)

一、需求

在Vue项目开发过程中,需要根据按钮的数量动态设置图标元素的宽度。

二、分析

el-col标签内,如果只显示一个图标元素,则将宽度设置为100%;

如果显示两个图标元素,则将宽度设置为50%;

等等.

三、解决方法

el-col v-for='(btn, index) in btnArr' :key='index' :style='{width: multiWidth}'./el-col

脚本

.

计算: {

多宽度() {

开关(选项.长度){

案例1:

返回100 + '%'

案例2:

返回50 + '%'

案例3:

返回33 + '%'

案例4:

返回25 + '%'

}

}

}

/脚本

有关计算的更多信息,请参考博文:

《Vue进阶(84):Vue中Compulated和Watch的使用和区别》

《Vue进阶(28):Vue中compute和method的区别浅析》。

还可以考虑使用class属性来实现样式的动态设置。

!DOCTYPE html

html

元字符集='utf-8'

titleVue 测试实例/标题

脚本src='https://cdn.staticfile.org/vue/2.2.2/vue.min.js'/script

风格

.text-危险{

宽度: 100px;

高度: 100px;

背景:红色;

}。积极的{

宽度: 100px;

高度: 100px;

颜色:绿色;

}

/风格

/头

身体

div id='应用程序'

div v-bind:class='[isTest ? errorClass : '',是否处于活动状态? activeClass : '']'ceshi/div

/div

脚本

新Vue({

el: '#app',

数据: {

isActive: 为真,

isTest:true,

activeClass: '活动',

errorClass: '文本危险'

}

})

/脚本

/身体

/html

四、动态样式设置

注意事项:

所有带-的样式属性名称必须改为驼峰式大小写,例如font-size必须改为fontSize;

除绑定值外,其他属性值都应该用引号括起来,例如backgroundColor:'#00a2ff'而不是backgroundColor:#00a2ff;

4.1 对象

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

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

4.2 数组

html :style='[baseStyles, overrideStyles]'

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

4.3 三目运算符

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

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

4.4 多重值

此时浏览器会根据运行支持做出选择

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

4.5 绑定data对象

html :style='styleObject'

数据() {

返回{

样式对象: {

color: '红色',

字体大小:'13px'

}

}

}

五、拓展阅读

《Vue进阶(84):Vue中Compulated和Watch的使用和区别》

《Vue进阶(二十八):浅析Vue中compute和method的区别》

the end
免责声明:本文不代表本站的观点和立场,如有侵权请联系本站删除!本站仅提供信息存储空间服务。