(文章目录)

一、需求

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

二、分析

el-col标签内,若只展示1个icon元素的话,则设置宽度为100%; 若显示2个icon元素的话,则设置宽度为50%; 以此类推...

三、解决方法

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

<script>
...
computed: {
	multiWidth () {
		switch (option.length) {
			case 1:
				return 100 + '%'
			case 2:
				return 50 + '%'
			case 3:
				return 33 + '%'
			case 4:
				return 25 + '%'
		}
	}
}
</script>

有关computed,详参博文:

Vue进阶(八十四):vue中Computed 和 Watch的使用和区别》 《Vue进阶(二十八):浅析Vue中computed与method的区别》。

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<style>
.text-danger {
	width: 100px;
	height: 100px;
	background: red;
}
.active {
	width: 100px;
	height: 100px;
	color: green;
}
</style>
</head>
<body>
<div id="app">
	<div v-bind:class="[isTest ? errorClass : '',isActive ? activeClass : '']">ceshi</div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    isActive: true,
	isTest:true,  
	activeClass: 'active',
    errorClass: 'text-danger'
  }
})
</script>
</body>
</html>

四、动态样式设置

注意事项:

  • 凡是有-style属性名都要变成驼峰式,比如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, overridingStyles]"
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"
data() {
    return{
      styleObject: {
        color: 'red',
        fontSize: '13px'
      }  
    }
}

五、拓展阅读