以下是一个简化版的Vue组件,用于创建一个通用的表格组件,它包含表头(columns)和数据(dataSource)两个主要属性。
<template>
  <div class="common-table">
    <table>
      <thead>
        <tr>
          <th v-for="column in columns" :key="column.key">
            {{ column.title }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="row in dataSource" :key="row.key">
          <td v-for="column in columns" :key="column.dataIndex">
            {{ row[column.dataIndex] }}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
 
<script>
export default {
  name: 'CommonTable',
  props: {
    columns: {
      type: Array,
      required: true
    },
    dataSource: {
      type: Array,
      required: true
    }
  }
}
</script>
 
<style scoped>
.common-table table {
  width: 100%;
  border-collapse: collapse;
}
 
.common-table th, .common-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}
 
.common-table tr:nth-child(even) {
  background-color: #f2f2f2;
}
</style>使用此组件时,你需要传递columns和dataSource属性,其中columns是一个对象数组,定义了表头的信息,包括标题(title)和数据索引(dataIndex),而dataSource是一个对象数组,包含了表格的数据。
例如,使用该组件的方式如下:
<template>
  <common-table :columns="tableColumns" :data-source="tableData"></common-table>
</template>
 
<script>
import CommonTable from './CommonTable.vue';
 
export default {
  components: {
    CommonTable
  },
  data() {
    return {
      tableColumns: [
        { title: 'Name', dataIndex: 'name', key: 'name' },
        { title: 'Age', dataIndex: 'age', key: 'age' },
        { title: 'Address', dataIndex: 'address', key: 'address' }
      ],
      tableData: [
        { key: '1', name: 'John Doe', age: 32, address: '123 Street' },
        { key: '2', name: 'Jane Smith', age: 28, address: '456 Avenue' }
      ]
    };
  }
};
</script>这个组件提供了一个基本的表格展示,你可以根据实际需求进一步扩展其功能,例如添加排序、筛选、分页等功能。