Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

如何简单实现一个类似于 element-ui table 组件

<wxTable :tableData="[{title:'石锤',file:'石锤.pdf'}]">
       <wx-column  label="部件名称" prop="title"></wx-column>
       <wx-column  label="文件名称" prop="file"></wx-column>
     </wxTable>

想用这个组件 渲染出这样的表格(要求 tableData 可扩展)
image.png

请教各位大佬给个思路
主要是内部的 wx-column 没思路

已经搞定了基础版本
求指教 wx-column 如何绑定自定义事件??????


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

其实你要做的事很简单,就是把你那一串html组织成能方便渲染的二维数组而已。
实现的方法可多了,我提供一个简单的方案,可以通过把column直接提交给table来进行数据集中处理后渲染表格

WxColumn.vue
<template>
  <span/>
</template>
<script>
  export default {
    name: 'WxColumn',
    props: {
      label: String,
      prop: String,
    },
    beforeCreate() {
      this.$parent.columns.push(this);
    },
    beforeDestroy() {
      const index = this.$parent.columns.indexOf(this);
      if (index > -1) {
        this.$parent.columns.splice(index, 1);
      }
    },
  };
</script>
WxTable.vue
<template>
  <table>
    <tr>
      <th
        v-for="(column, index) in columns"
        :key="`th-${column.label}${column.prop}${index}`"
      >
        {{ column.label }}
      </th>
    </tr>
    <tr
      v-for="(cols, $index) in rows"
      :key="`tr-${$index}`"
    >
      <td
        v-for="col in cols"
        :key="`td-${col.label}${col.prop}${$index}${col.value}`"
      >
        {{ col.value }}
      </td>
    </tr>
    <slot/>
  </table>
</template>
<script>
  export default {
    name: 'WxTable ',
    props: {
      tableData: {
        type: Array,
        default: () => [],
      },
    },
    data() {
      return {
        columns: [],
      };
    },
    computed: {
      rows() {
        return this.tableData.map(item =>
          this.columns.map(column => ({...column, value: item[column.prop]})),
        );
      },
    },
  };
</script>

离能真正工作还有很多细节要处理,但已经能组织出你要的表格架构了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...