需求:把表格第2、3列的文字,加上颜色
第1列 |
第2列 |
第3列 |
第4列 |
标题1 |
10 |
20 |
30 |
标题2 |
40 |
50 |
60 |
#后台配置color,可能不止是2、3列变色!
items: {
"list": [
["标题1", 10, 20, 30],
["标题2", 40, 50, 60],
["标题3", 70, 80, 90],
],
"color": [
{
"index": 1,
"color": "#2c86eb"
},
{
"index": 2,
"color": "#ffa500"
}
]
}
Vue第一种实现 v-html
<table>
<template v-for="(rows,index) in items.list">
<tr :key="index">
<template v-for="(row,idx) in rows">
<td :key="idx" v-html="color(row,idx,items)"></td>
</template>
</tr>
</template>
</table>
methods: {
color(row, idx, items) {
let obj = {};
let color = items.color.filter(d => d.index === idx);
obj = {value: row, idx, color: color.length ? color[0].color : ''};
return `<span style="color:${obj.color}">${obj.value}</span>`
}
}
Vue第二种实现 自定义组件
<table>
<template v-for="(rows,index) in items.list">
<tr :key="index">
<template v-for="(row,idx) in rows">
<td :key="idx">
<row :idx="idx" :row="row" :items="items"/>
</td>
</template>
</tr>
</template>
</table>
<template>
<span :style="{'color':color.length ? color[0].color : ''}">{
{ row }}</span>
</template>
<script>
export default {
name: 'Row',
props: {
idx: Number,
row: String,
items: Object,
},
computed: {
color() {
return this.items.color.filter(d => d.index === this.idx)
}
}
}
</script>
Vue第三种实现 css3 (适合小程序)
# class=rows里面的结构可以看出,有颜色的span在上面,隐藏没颜色的span就可以了
<table>
<template v-for="(rows,index) in items.list">
<tr :key="index">
<template v-for="(row,idx) in rows">
<td class="rows" :key="idx">
<template v-for="obj in items.color">
<span v-if="obj.index===idx" :style="{'color':obj.color}">{
{ row }}</span>
</template>
<span>{
{ row }}</span>
</td>
</template>
</tr>
</template>
</table>
#从td里找第二个span,然后隐藏
<style scoped>
.rows span:nth-child(2) {
display: none;
}
</style>