本文介绍: 根据需求写的表单+表格,由于后端给的格式适应表格数据格式,做了很多转换最后提交数据也做了格式转换

首先一个demo,请大佬教的

<template>
    <view>
        <el-button type="primary" @click='tableData.push(obj)'>新增行</el-button>
        <el-button type="primary" @click='gettableData'&gt;获取完整信息</el-button&gt;
        <el-table :data="tableData" style="width: 100%"&gt;
            <el-table-column prop="date" label="日期" width="180">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.date" @change='getChange(scope.row)' placeholder="请输入内容"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="180">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.name" placeholder="请输入内容"></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="address" label="地址">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.address" placeholder="请输入内容"></el-input>
                </template>
            </el-table-column>
            <el-table-column :prop="item.name" :label="item.title" v-for="(item,idx) in titleList" :key="idx">
                <template slot-scope="scope">
                    <el-input v-model="scope.row[item.name]" placeholder="请输入内容"></el-input>
                </template>
            </el-table-column>
        </el-table>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                obj: {
                    date: '',
                    name: '',
                    address: ''
                },
                tableData: [],
                titleList: []
            }
        },
        onLoad() {
            this.getList()
        },
        methods: {
            gettableData() {
                console.log('全部数据', this.tableData)
            },
            getChange(val) {
                console.log('当前行数据', val)
            },
            getList() {
                //假设这里获取前段行数据
                this.tableData = [{
                    date: '2016-05-02',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1518 弄'
                }, {
                    date: '2016-05-04',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1517 弄'
                }, {
                    date: '2016-05-01',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1519 弄'
                }, {
                    date: '2016-05-03',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1516 弄'
                }]
                
                
                //假设行数获取完成后获取表头
                
                this.titleList = [{
                    title: '动态表头1',
                    name: 'ziduan1'
                }, {
                    title: '动态表头2',
                    name: 'ziduan2'
                }, {
                    title: '动态表头3',
                    name: 'ziduan3'
                }]
                
                
                //表头行数据都获取完成之后进行预处理
                
                this.tableData.forEach(data=>{
                    this.titleList.forEach(item=>{
                        data[item.name]=''
                    })
                })
                
                //拼接好的数据
                console.log(this.tableData)
                
            },
        }
    }
</script>

<style scoped lang="less">

</style>

接下来是根据需求写的表单+表格,由于后端给的格式不适应表格数据格式,做了很多转换最后提交数据也做了格式转换代码较糙,留着看看长个记性,毕竟折磨了好多天

页面效果

<script lang='ts' setup>
import PageHeader from '@/components/header/PageHeader.vue'
import CustomButton from '@/components/button/CustomButton.vue'
import MySearchInput from '@/components/search/MySearchInput.vue'
import AdvancedSearch from '@/components/search/AdvancedSearch.vue'
import { ref, reactive, toRaw, watch } from 'vue'
import { ElTable, ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import router from '@/router'
import type { material } from '@/types/material'
import { getConversionList, addAdjust } from '@/api/material'
import { typrList } from '@/api/fieldType'
import type { TableColumnCtx } from 'element-plus/es/components/table/src/table-column/defaults'
import { notifyAPIResponse } from '@/utils/common'



const dialogFormVisible = ref(false),
    arr: any = ref([]),
    arr1: any = ref([]),
    currentIndex = ref()
const advanceSearchConfig = {
    formType: [
        {
            label: 'value',
            key: 'search',
            compType: 'ElInput',
            value: '',
        },
    ]
}


// do not use same name with ref
const form = reactive({
    adjustState: '0',
    adjustTime: '',
    createBy: '',
})
const rules = reactive({
    createName: [
        {
            required: true,
            message: '请输入必填项'
        }
    ]
})
const cancel = () => {
    router.push({
        path: '/MaterialConversion/conversion'
    })
}

//获取物料类型列表转换数组渲染表头
const getArrList = async () => {
    await typrList('').then(res => {
        arr.value = res.rows
        console.log(arr.value);
        for (let i of arr.value) {
            let obj1 = {
                name: i.typeName + '编码',
                typeId: i.typeId,
            }

            let obj2 = {
                name: i.typeName + '名称',
                typeId: i.typeId,
            }

            arr1.value.push(obj1)
            arr1.value.push(obj2)
        }
    })

    onload()
    console.log(arr1.value, 'arr1');

}
getArrList()

const onload = () => {
    //@ts-ignore
    form1.tableData1.forEach(data => {
        //@ts-ignore
        arr1.value.forEach(item => {
            data[item.name] = ''
        })
    })
}

//获取物料信息const getMerList = async () => {
    const { rows: list, total } = await getConversionList({
        ...toRaw(pageConfig),
        ...route.query,
    }).catch(() => { })

    tableData.value = list
    pageConfig.total = total
}

// 物料页码跳转
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)

    pageConfig.pageSize = val

    router.push({
        query: {
            ...route.query,
            ...pageConfig,
        },
    })
}

const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)

    pageConfig.pageNum = val

    router.push({
        query: {
            ...route.query,
            ...pageConfig,
        },
    })
}

const pageConfig = reactive({
    pageNum: 1,
    pageSize: 20,
    total: 0,
})


//明细页码跳转
const pageConfig1 = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0,
})
const handleSizeChange1 = (val: number) => {
    console.log(`${val} items per page`)
    pageConfig.pageSize = val

}

const handleCurrentChange1 = (val: number) => {
    console.log(`current page: ${val}`)
    pageConfig.pageNum = val

}


const tableRef = ref<InstanceType<typeof ElTable>>(),
    tableData = ref<Array<material>>([]),
    route = useRoute(),
    loading = ref(true),
    form1: any = reactive({
        tableData1: []
    }),
    selectedNames: any = ref([])

watch(
    () => route.query,
    () => {
        getMerList()
    }
)





const addLine = () => {
    let dataline = {
        state: '0',
        materialNumber: '',
        materialName: '',
    }
    let dataline1 = {
        state: '',
        materialNumber: '',
        materialName: '',
    }
    //@ts-ignore
    form1.tableData1.push(dataline)
    form1.tableData1.push(dataline1)

    console.log(form1.tableData1, 'qqq');

}

interface SpanMethodProps {
    row: material
    column: TableColumnCtx<material>
    rowIndex: number
    columnIndex: number
}

const objectSpanMethod = ({
    row,
    column,
    rowIndex,
    columnIndex,
}: SpanMethodProps) => {
    if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4) {
        if (rowIndex % 2 === 0) {
            return {
                rowspan: 2,
                colspan: 1,
            }
        } else {
            return {
                rowspan: 0,
                colspan: 0,
            }
        }
    }
}

const searchList = (current: any) => {
    // console.log(current, 'current');
    currentIndex.value = current
    dialogFormVisible.value = true
    getMerList()
}

const subSelected = () => {
    const rows = tableRef.value?.getSelectionRows()
    if (rows.length === 0 || rows.length > 1)
        return ElMessage.error('必须且只能选中一行')
    console.log(currentIndex.value);
    console.log(rows[0]);
    form1.tableData1[currentIndex.value].materialName = rows[0].materialName
    form1.tableData1[currentIndex.value].materialNumber = rows[0].materialNumber
    form1.tableData1[currentIndex.value].materialId = rows[0].materialId
    selectedNames.value = rows[0].names
    for (let i of selectedNames.value) {
        form1.tableData1[currentIndex.value][i.typeName + '编码'] = i.num
        form1.tableData1[currentIndex.value][i.typeName + '名称'] = i.name
    }

    console.log(form1.tableData1, '......');



    dialogFormVisible.value = false
}

const subdata = () => {
    let children: any = [],
        subobj = {}

    console.log(form1.tableData1, '88888888');

    for (let i = 0; i < form1.tableData1.length; i++) {
        if (i % 2 == 0) {
            let obj = {
                materialId: '',
                state: '',
                entries: []
            }
            obj.state = form1.tableData1[i].state
            obj.materialId = form1.tableData1[i].materialId
            children.push(obj)
        } else {
            for (let k = 0; k < arr1.value.length; k++) {
                if (arr1.value[k].name in form1.tableData1[i]) {
                    if (k % 2 == 0) {
                        let entriesObj = {
                            typeId: '',
                            name: '',
                            num: ''
                        }
                        entriesObj.typeId = arr1.value[k].typeId
                        entriesObj.name = form1.tableData1[i][arr.value[k / 2].typeName + '名称']
                        entriesObj.num = form1.tableData1[i][arr.value[k / 2].typeName + '编码']
                        // console.log(entriesObj, 'entriesObj');
                        console.log(children[(i - 1) / 2], 'children[i / 2]');
                        children[(i - 1) / 2].entries.push(entriesObj)
                    }
                }
            }
        }
    }

    console.log(children, 'childrenchildrenchildren');

    subobj = {
        children,
        ...form
    }

    notifyAPIResponse(() => addAdjust(subobj)).then((isOk) => {
        if (!isOk) return
        router.go(-1)
    })

}

// 选中某一行修改移除
const getDelIndex = (i: any) => {
    form1.tableData1.splice(i, 2)
}

</script>
 
<template>
    <div>
        <!-- MaterialConversion/addConversion -->
        <PageHeader>
            <template #left>
                <span class="title">物料转化方案调整单</span>
            </template>
            <template #right>
                <CustomButton type="plain">流程进度</CustomButton>
                <CustomButton type="plain">快速跳转</CustomButton>
            </template>
        </PageHeader>
        <a-card class="core">
            <div class="title1">基本信息</div>
            <div>
                <el-form :model="form" label-width="120px" ref="vForm" :rules="rules">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item label="单据时间">
                                <el-date-picker v-model="form.adjustTime" type="date" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="创建人" prop="createName">
                                <el-input v-model="form.createBy" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="状态">
                                <el-select v-model="form.adjustState" placeholder="请输入">
                                    <el-option label="创建" value="0" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </a-card>

        <a-card class="core">
            <div class="title1">明细信息</div>
            <header class="flex justify-between mt-5">
                <div>
                    <CustomButton type="plain" @click="addLine">新增行</CustomButton>
                    <CustomButton type="plain">删除行</CustomButton>
                </div>
            </header>
            <!-- 明细信息表格 -->

            <el-form :model="form1">
                <el-table ref="tableRef" :data="form1.tableData1" style="width: 100%" v-bind="$attrs"
                    :span-method="objectSpanMethod" :row-style="{ height: '40px' }">
                    <el-table-column type="selection" width="55" />
                    <el-table-column min-width="80" label="操作" align="center">
                        <template #default="scope">
                            <el-button text type="danger" @click="getDelIndex(scope.$index)">删除</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="150" label="状态">
                        <template #default="scope">
                            <el-select v-model="scope.row.state">
                                <el-option label="正常" value="0" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="150" label="物料编码">
                        <template #default="scope">
                            <el-input v-model="scope.row.materialNumber" style="width:150px">
                                <template #suffix>
                                    <Search style="width: 1em; height: 1em; margin-right: 8px" class="cursor-pointer"
                                        @click="searchList(scope.$index)" />
                                </template>
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="150" label="物料名称">
                        <template #default="scope">
                            <el-input v-model="scope.row.materialName" style="width:150px"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="150" v-for="item, i in arr1" :label="item.name" :prop="item.val" :key="i">
                        <template #default="scope">
                            <span v-show="scope.$index % 2 == 0">
                                <el-input v-model="scope.row[item.name]" style="width:150px" disabled></el-input>
                                <!-- {{ scope.row[item.name] || '' }} -->
                            </span>
                            <el-input v-model="scope.row[item.name]" style="width:150px" v-show="scope.$index % 2 !== 0">
                            </el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <div class="mt-2">
                <el-pagination v-model:currentPage="pageConfig1.pageNum" v-model:page-size="pageConfig1.pageSize"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pageConfig1.total" @size-change="handleSizeChange1" @current-change="handleCurrentChange1" />
            </div>
        </a-card>

        <el-dialog v-model="dialogFormVisible" title="选择物料" class="pb-6" width="40%">
            <div class="flex justify-end items-center">
                <MySearchInput class="ml-8" main-name="search"></MySearchInput>
                <AdvancedSearch class="ml-8" :formType="advanceSearchConfig.formType"></AdvancedSearch>
            </div>
            <el-table :data="tableData" max-height="500px" ref="tableRef">
                <el-table-column type="selection" />
                <el-table-column prop="materialName" label="物料名称" min-width="150" />
                <el-table-column prop="materialNumber" label="物料编码" min-width="150" />
                <el-table-column prop="materialFName" label="ERP物料名称" min-width="150" />
                <el-table-column prop="materialFNumber" label="ERP物料编码" min-width="150" />
            </el-table>
            <div class="mt-2">
                <el-pagination v-model:currentPage="pageConfig.pageNum" v-model:page-size="pageConfig.pageSize"
                    :page-sizes="[20, 30, 40, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pageConfig.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
            <div style="float:right" class="mt-2">
                <el-button @click="dialogFormVisible = false">关闭</el-button>
                <el-button type="primary" @click="subSelected">确定</el-button>
            </div>
        </el-dialog>

        <a-card class="footer flex justify-end">
            <CustomButton type="plain" @click="cancel">取消</CustomButton>
            <!-- <CustomButton type="plain">保存</CustomButton> -->
            <CustomButton type="primary" @click="subdata">提交</CustomButton>
        </a-card>
    </div>
</template>
 
<style lang = "scss" scoped>
.title {
    font-size: 20px;
    margin-left: 10px;
}

.title1 {
    font-size: 16px;
    font-weight: 700;
}

.core {
    margin: 0 8px 8px 8px;
}

:deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 100%
}

.footer {
    margin: 0 8px 8px 8px;
}

:deep(.ant-card-body) {
    padding: 10px;
}

.el-table .cell {
    display: flex;
    align-items: center;
}

.el-pagination {
    justify-content: end;
}

.el-pagination__total {
    margin-right: auto !important;
}

.el-table--fit {
    margin-top: 20px;
    border-top: 1px solid var(--el-border-color-lighter);
}
</style>

原文地址:https://blog.csdn.net/qq_56366747/article/details/129427619

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_7787.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注