demand

During the development of Vue project, the width of icon element needs to be dynamically set according to the number of buttons.

Analysis of the

In the el-Col tag, if only one icon element is displayed, set the width to 100%; If 2 icon elements are displayed, set the width to 50%; And so on…

The solution

<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>Copy the code

For more information about computed tomography, please refer to blog post: “Vue Progression (84) : Use and Difference between computed And Watch in Vue” “Vue Progression (28) : Brief Analysis of the difference between computed and Method in Vue”.

You can also consider using the class attribute for dynamic style setting.

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script SRC = "https://cdn.staticfile.org/vue/2.2.2/vue.min.js" > < / script > < style >. The text - danger {width: 100 px; 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>Copy the code