Vue进阶(幺伍玖):动态样式设置

248 阅读1分钟

需求

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>