在vue项目中对于大量查询出来的数据有时候会要求根据条件进行不同样式的展示(一般也就是大屏展示的时候),不可能将相同的代码进行多次样式的绑定,利用v-if或者v-show的形式一次展示,这样一来会显得代码非常臃肿,哈哈哈哈,当然看起来也不是很高级,也就是很容易将自己的水平暴露给别人哈,那么如何解决呢?如下:
1.直接进行style绑定
在标签上进行样式绑定
<li :style="getStyle(item)" v-for="(item,index) in data" :key="index"></li>
然后在methods中去实现它就好了
methods:{
getStyle(item){
if(item.active){ //active是用来说明是否是当前元素,当前元素给true
return {'border':'2px solid #ddb48a',"border-radius": "6px"}
}
return {}
}
}
2.动态绑定:class
动态绑定肯定是有条件哒,自然就会想到三元运算法(条件?条件成立时:条件不成立时),它也是一个比较方便而且使用也很频繁的表达式,那么就用它啦。
:class="this.validateTextLength(name) > 6 ? 'class1': 'class2'"
顺便安利一个判断字符串长度的方法(注意:汉语与英语是不一样的),不过这个是我翻译别人的,链接找不到了,如有不妥敬请见谅。
methods:{
validateTextLength (value) {
let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g
let mat = value.match(cnReg)
let length
if (mat) {
length = (mat.length + (value.length - mat.length) * 0.5)
return length
} else {
return value.length * 0.5
}
}
}