Vue3 ElementPlus 动态表单点击按钮新增/删除行

前言

 

element-plus版本为1.1.0-beta.20,vue版本为3.2.20。不同版本代码实现可能会有差异

参考链接:

Elementui官网-Form表单-动态增减表单项:

https://element-plus.gitee.io/zh-CN/component/form.html#%E5%8A%A8%E6%80%81%E5%A2%9E%E5%87%8F%E8%A1%A8%E5%8D%95%E9%A1%B9

效果截图

Vue3 ElementPlus 动态表单点击按钮新增/删除行

代码实现

思路:在el-form表单中,利用v-for循环数据,点击新增或删除按钮时,更新v-for的值,实现动态增减行。

完整代码

<template>
    <el-form :model="ruleForm" status-icon ref="formRef" label-width="120px">
        <el-row :gutter="20">
            <el-col :span="4">
                <el-form-item>
                    <el-button type="primary" @click="addFruitConfig">新增行</el-button>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="20" v-for="(item, index) in ruleForm.fruitConfig">
            <el-col :span="10">
                <el-form-item label="水果名称" prop="'fruit' + index">
                    <el-input type="text" v-model="item.fruit" autocomplete="off" maxlength="50">
                    </el-input>
                </el-form-item>
            </el-col>
            <el-col :span="10">
                <el-form-item label="水果售价" prop="'price' + index">
                    <el-input type="text" v-model="item.price" autocomplete="off" maxlength="50">
                    </el-input>
                </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-button @click.prevent="removeFruitConfig(item)">删除行</el-button>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="4">
                <el-form-item>
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</template>

<script setup>
    import {
        reactive,
        toRefs,
        ref,
    } from 'vue';

    // 参数声明
    const formRef = ref(null);
    const state = reactive({
        ruleForm: {
            fruitConfig: [{
                fruit: '',
                price: ''
            }]
        },
    })


    const addFruitConfig = () => { // 新增水果、售价行
        state.ruleForm.fruitConfig.push({
            fruit: '',
            price: ''
        })
    }

    const removeFruitConfig = (item) => { // 删除水果、售价行
        const index = state.ruleForm.fruitConfig.indexOf(item)
        if (index !== -1) {
            state.ruleForm.fruitConfig.splice(index, 1)
        }
    }

    const submitForm = () => { // 点击确定按钮,输出行内数据
        var fruitConfig = state.ruleForm.fruitConfig;
        console.log(fruitConfig);
        console.log("水果名称:" + fruitConfig[0].fruit);
        console.log("水果售价:" + fruitConfig[0].price);
    }

    // 数据解构
    const {
        ruleForm,
        rules
    } = {
        ...toRefs(state)
    };
</script>

<style scoped>
</style>

 

上一篇:使用 node xlsx 获取 xlsx文件数据


下一篇:Android 开发必备知识:我和 Gradle 有个约会