---
date: 2022-04-17
title: Vue3 通过 JSON 渲染 ElementUI Table 组件的列
category: experience
cover: https://tse1-mm.cn.bing.net/th/id/OIP-C.Ko-vkqS8ZJSwVrq2tIf1igHaDt?pid=ImgDet&rs=1
location: 甘肃
tags:

- Vue3
- Render
- ElementUI

---

起因是要做一个需要自定义表格列的一个项目。就研究了一下怎么通过 `Json` 封装来渲染本来需要插槽才能渲染的功能。

```vue
<!-- App.vue -->
<template>
  <Sqtable v-model="tableData" :columns="tableColumns"/> <!-- 自定义组件 -->
</template>

<script setup>
import {ref} from "vue"
import Sqtable from "./Sqtable.jsx" // 引入自定义组件

// 表格数据
const tableData = ref([
  {
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-02',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-04',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
])
// 列数据
const tableColumns = [
  {
    label: "姓名",
    prop: "name"
  },
  {
    label: "日期",
    prop: "date"
  },
  {
    label: "地址",
    prop: "address"
  }
]
</script>
```

```jsx
// Sqtable.jsx
import {defineComponent, ref} from "vue";

export default defineComponent({
    props: {
        modelValue: Array,
        columns: Array,
    },

    setup(props) {
        const data = ref(props.modelValue);
        const columns = ref(props.columns);

        return {
            data,
            columns
        };
    },

    render() {
        return (
            <el-table data={this.data}>
                {
                    this.columns.map((e) => {
                        return (
                            <el-table-column prop={e.prop} label={e.label}/>
                        )
                    })
                }
            </el-table>
        );
    }
});
```