el-table动态表头与模拟请求数据

<el-table
            :data="tableData" style="width: 100%"
        >
            <el-table-column
                v-for="column in dynamicColumns"
                :key="column.prop"
                :prop="column.prop"
                :label="column.label"
                :width="column.width"
            >
                <template #default="{row, column, $index}">
                    <span v-if="column.label === '对比列'">{{ row[column.prop] }}span>
                    <template v-else>
                        <div class="image-description">
                            <img
                                :src="row.imageAndDescription.imageUrl"
                                alt="Image"
                                style="max-width: 100%;
                                max-height: 100px;"
                            >
                            <div>{{ row.imageAndDescription.description }}div>
                        div>
                    template>
                template>
            el-table-column>

            
            
        el-table>

模拟请求数据

const tableData = ref([]);
// 从接口获取表头数据
const dynamicColumns = ref([]);

onMounted(async () => {
    try {
        const res = await fetchDataFromApi();
        dynamicColumns.value = res.data.columns;
        tableData.value = res.data.tableData;
    }
    catch (error) {
        console.error('Error fetching data', error);
    }
});

// 模拟一个获取数据的函数
function fetchDataFromApi() {
    return new Promise(resolve => {
        // 模拟接口响应
        setTimeout(() => {
            resolve({
                data: {
                    columns: [
                        {prop: 'title', label: '对比列', width: '180'},
                        {prop: 'imageAndDescription', label: '标注任务1', width: '300'},
                        {prop: 'imageAndDescription', label: '标注任务2', width: '300'},
                        {prop: 'imageAndDescription', label: '标注任务3'},
                    ],
                    tableData: [
                        {title: '狗', imageAndDescription: {imageUrl: 'https://example.com/dog.jpg', description: '这只狗很可爱,高清图。'}},
                        {title: '猫', imageAndDescription: {imageUrl: 'https://example.com/cat.jpg', description: '这只猫也很可爱,高清图。'}},
                        {title: '猫', imageAndDescription: {imageUrl: 'https://example.com/cat.jpg', description: '这只猫也很可爱,高清图。'}},
                        {title: '猫', imageAndDescription: {imageUrl: 'https://example.com/cat.jpg', description: '这只猫也很可爱,高清图。'}},
                    ],
                },
            });
        }, 1000);
    });
}

// const dynamicColumns = ref([
//     {prop: 'date', label: '对比列', width: '180'},
//     {prop: 'name', label: '标注任务1', width: '180'},
//     {prop: 'address', label: '标注任务2'},
// ]);

你可能感兴趣的:(vue.js,前端,javascript)