Vue匹配数据字典/封装组件(小demo)

需求:把表格第2、3列的文字,加上颜色
第1列第2列第3列第4列
标题1102030
标题2405060
#后台配置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>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值