遇到的问题:如题
展示效果:
技术背景:vue3.0
直接上代码
<template>
<div class="flex w-full" v-if="dataSource.length > 0">
<!-- 表头 -->
<div style="width: 248px">
<!--表头-->
<table width="100%">
<tr><td class="left_title bgGray">时间段</td></tr>
<tr v-for="(item, index) in tableHeader" :key="index"
><td class="left_title bgBlue" :class="index % 2 == 0 ? 'bgBlue' : 'bgGray'">{{
item
}}</td></tr
>
<tr><td class="left_title bgGray">操作</td></tr>
</table>
</div>
<!--表格body-->
<div v-for="(item, index) in dataSource" :key="index" class="flex-1 w-full">
<table width="100%">
<tr
><td class="black_title bgGray">
{{ item.time }}
</td></tr
>
<tr v-for="(headerItem, indexKey) in tableHeader" :key="indexKey"
><td class="black_title" :class="indexKey % 2 == 0 ? 'bgBlue' : ''">
<Input
v-if="editableData[item.id]"
v-model:value="editableData[item.id][headerItem]"
/>
<template v-else>
{{ item[headerItem] }}
</template>
</td></tr
>
<tr
><td class="black_title">
<span v-if="editableData[item.id]">
<a @click="save(item.id)" class="mr-20px">保存</a>
<a @click="cancel(item.id)">取消</a>
</span>
<span v-else>
<a @click="edit(item.id)" class="mr-20px">编辑</a>
<a @click="remove(item.id)">删除</a>
</span>
</td></tr
>
</table>
</div>
</div>
</template>
setup
<script lang="ts" setup>
const dataSource: Item[] = ref([]);
const tableHeader: [] = ref([]);
// 获取数据
async function getTable() {
// if (!state.start || !state.end) {
// return message.warn('请选择时间!');
// }
let params = {
...state,
id: props.tasId,
};
let tempData = await GetHistoryRes(params);
// 数据处理
tempData.map((item, index) => {
let obj: any = {};
item.values.map((items) => {
obj[items.name] = items.value;
if (index == 0) {
tableHeader.value.push(items.name);
}
list.push(items);
});
dataSource.value.push({
time: item.time,
...obj,
id: buildUUID(),
});
xData.value.push(item.time);
});
}
// 编辑
const edit = (key: string) => {
editableData[key] = cloneDeep(
dataSource.value.filter((item) => {
return key === item.id;
})[0],
);
};
// 删除
const remove = (key: string) => {
dataSource.value = dataSource.value.filter((item) => {
return key !== item.id;
});
};
// 保存
const save = (key: string) => {
Object.assign(dataSource.value.filter((item) => key === item.id)[0], editableData[key]);
delete editableData[key];
console.log(dataSource.value);
};
// 取消
const cancel = (key: string) => {
delete editableData[key];
};
</script>
less
<style scoped lang="less">
@prefix-cls: ~'@{namespace}-vertical-table';
.@{prefix-cls} {
.black_title,
.left_title {
height: 40px;
line-height: 40px;
text-align: center;
border: 1px solid #e5e6eb;
}
.bgGray {
background: #f2f3f5;
}
.bgBlue {
background: #e8f3ff;
}
}
</style>