layui动态添加输入框_VUE动态添加elformitem

be7d230496e660429518d8d987c82d9b.png

功能简介:

    VUE结合elementUI动态生成form表单

    文件上传验证

    input输入框非空校验

    添加按钮:校验一次只能添加一行

    删除按钮:若删除的行有内容给予提示,若为空直接删除

    动态给予按钮提示语:点击添加,请完成未填写的内容,点击删除...

代码示例

<template>    <div class="app-container">        <div class="filter-container">            <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate" size="mini">                创建            el-button>        div>        <el-dialog :title="dialogStatusMap[dialogStatus] ? dialogStatusMap[dialogStatus].value : ''" :visible.sync="dialogFormVisible" width="55%">            <template v-if="dialogStatus === dialogStatusMap.create.key || dialogStatus === dialogStatusMap.edit.key">                <el-form ref="dataForm" :model="teamConfigFormData" label-width="100px"                          size="mini">                    <div class="moreRules">                        <div class="moreRulesIn" v-for="(item, index) in teamConfigFormData.teamConfigList" :key="item.key">                            <el-row>                                <el-col :span="2.5">                                    <el-form-item label="图标" :prop="'teamConfigList.' + index +'.iconFile'" @click.native="getIndexVal(index)">                                        <el-tooltip id="smallCss" effect="dark" content="文件格式:PNG 大小:1M以内" placement="top">                                            <el-upload                                                    :before-upload="beforeIconUpload"                                                    drag                                                    class="app-icon-uploader"                                                    action="action"                                                    :http-request="handleUploadingIcon"                                                    :show-file-list="false">                                                <img v-if="teamConfigFormData.teamConfigList[index].icon" :src="teamConfigFormData.teamConfigList[index].icon" style="width:28px; height: 28px">                                                <i v-else class="el-icon-plus" >i>                                            el-upload>                                        el-tooltip>                                    el-form-item>                                el-col>                                <el-col :span="8">                                    <el-form-item class="rules" label="项目KEY" :prop="'teamConfigList.' + index +'.teamKey'" :rules="[{required: true, message: '项目KEY是必填项'}]">                                        <el-input v-model="item.teamKey" placeholder="项目KEY" class="el-select_box">el-input>                                    el-form-item>                                el-col>                                <el-col :span="8">                                    <el-form-item class="rules" label="项目名称" :prop="'teamConfigList.' + index +'.teamName'" :rules="[{required: true, message: '项目名称是必填项'}]">                                        <el-input v-model="item.teamName" placeholder="项目名称" class="el-select_box">el-input>                                    el-form-item>                                el-col>                                <el-col :span="1">                                    <el-tooltip class="item" effect="dark" :content="addButtonMessage" placement="top">                                        <el-button v-show="index === 0" @click="addTeamConfig" @mouseenter.native="verifyAddButton()" size="mini" type="primary" icon="el-icon-plus" circle style="margin-left: 20%">el-button>                                    el-tooltip>                                    <el-tooltip class="item" effect="dark" :content="delButtonMessage" placement="top">                                        <el-button v-show="index > 0" @click="deleteTeamConfig(item, index)" @mouseenter.native="verifyDeleteButton(item)" size="mini" type="danger" icon="el-icon-delete" circle style="margin-left: 20%">el-button>                                    el-tooltip>                                el-col>                            el-row>                        div>                    div>                el-form>                <div slot="footer" class="dialog-footer">                    <el-button @click="showValue" size="mini" type="primary">                        ShowValue                    el-button>                    <el-button @click="addTeamConfig" size="mini" type="primary">                        添加                    el-button>                    <el-button @click="dialogFormVisible = false" size="mini">                        取消                    el-button>                    <el-button type="primary" @click="dialogStatus === dialogStatusMap.create.key?saveApplication():updateData()" size="mini">                        保存                    el-button>                div>            template>        el-dialog>    div>template><script>import {getAppInfos, insertAppInfo, updateAppInfo} from '@/api/euser-admin/team-admin';import waves from '@/directive/waves'; // waves directiveimport Pagination from '@/components/Pagination';import {dataStatusEnum} from '@/common/constant';import {uploadFile} from "@/api/app-store/file";import {getFileUrl} from "@/utils/file";const dialogStatusMap = {    edit: {key: 'edit', value: '编辑'},    create: {key: 'create', value: '创建'}};export default {    name: 'app-info',    components: {Pagination},    directives: {waves},    filters: {        statusTagFilter(status) {            let item = dataStatusEnum.find(item => item.key === status);            if (item) {                return item.tagType;            } else {                return status;            }        },        statusFilter(status) {            let item = dataStatusEnum.find(item => item.key === status);            if (item) {                return item.label;            } else {                return status;            }        }    },    data() {        return {            //-------租户配置的数据-begin-----------            disabledVal: false,            addButtonMessage: "点击添加",            delButtonMessage: "点击删除",            isAddNullValue: true,            isDeleteNullValue: true,            indexVal: undefined,            teamConfigFormData: {                configId: '我是配置Id',                teamConfigList: [{                    teamKey: '',                    teamName: '',                    icon: undefined,                    iconFile: undefined,                    /*teamURL: '',*/                }]            },            //-------租户配置的数据-end-------------        };    },    created() {        this.initData();        // this.getAppInfos();    },    methods: {        //-------租户配置的methods-begin-----------        getIndexVal(index) {            this.indexVal = index;            console.log("this.indexVal = index")            console.log(this.indexVal)        },        handleUploadingIcon(item) {            console.log("---item-----")            console.log(item)            this.teamConfigFormData.teamConfigList[this.indexVal].iconFile = item.file;            this.teamConfigFormData.teamConfigList[this.indexVal].icon = URL.createObjectURL(item.file);            // 刷新数据            this.$forceUpdate();        },        // 校验图片        beforeIconUpload(file) {            const isPNG = file.type === 'image/png';            const isLt1M = file.size / 1024 / 1024 < 1;            if (!isPNG) {                this.$message.error('上传图片只能是 PNG 格式!');            }            if (!isLt1M) {                this.$message.error('上传图片大小不能超过 1MB!');            }            return isPNG && isLt1M;        },        // 校验删除按钮        verifyDeleteButton(item) {            console.log("------item, index--------")            console.log(item);            let teamKey = item.teamKey;            let teamName = item.teamName;            if (teamKey) {                this.isDeleteNullValue = false;            } else if (teamName) {                this.isDeleteNullValue = false;            } else {                this.isDeleteNullValue = true;            }        },        // 校验添加按钮是否有效        verifyAddButton() {            let lastIndex = this.teamConfigFormData.teamConfigList.length;            let teamConfigList = this.teamConfigFormData.teamConfigList;            if (lastIndex > 0) {                for (let j = 0; j < lastIndex; j++) {                    let teamConfigListElement = teamConfigList[j];                    let teamKey = teamConfigListElement.teamKey;                    let teamName = teamConfigListElement.teamName;                    this.isAddNullValue = teamKey && teamName;                    if (this.isAddNullValue) {                        this.addButtonMessage = "点击添加"                    } else {                        this.addButtonMessage = "请完成未填写的内容"                        return;                    }                }            }        },        // 显示值        showValue() {            console.log("this.teamConfigFormData ======")            console.log(this.teamConfigFormData)            let length = this.teamConfigFormData.teamConfigList.length;            for (let i = 0; i < length; i++) {                let iconFile = this.teamConfigFormData.teamConfigList[i].iconFile;                if (i === 1) {                    iconFile = '';                }                if (!iconFile) {                    console.log(i + "    ---iconFile  没有value--")                    console.log(iconFile)                    continue;                } else {                    console.log(i + "    ---iconFile  +++++++有value--")                    console.log(iconFile)                }            }        },        // 数据初始化        initData() {            this.teamConfigFormData.teamConfigList = []        },        // 点击新增按钮        addTeamConfig() {            // 验证参数            this.verifyAddButton()            if (this.isAddNullValue) {                this.teamConfigFormData.teamConfigList.push({                    teamKey: '',                    teamName: '',                    iconFile: undefined,                })            }        },        // 点新建按钮时的初始化         addInitTeamConfig() {            this.teamConfigFormData.teamConfigList.push({                teamKey: '',                teamName: '',                iconFile: undefined,            })        },        // 删除行        deleteTeamConfig(item, index) {            // 被删除的input是否有值            this.verifyDeleteButton(item);            if (this.isDeleteNullValue) {                // 空值直接删除                this.index = this.teamConfigFormData.teamConfigList.indexOf(item)                if (index !== -1) {                    this.teamConfigFormData.teamConfigList.splice(index, 1)                }            } else {                // 有值给予提示                this.tooltipDelete(item, index);            }        },        tooltipDelete(item, index) {            this.$confirm('是否移除您刚填写的值?', '提示', {                confirmButtonText: '确定',                cancelButtonText: '取消',                type: 'warning'            }).then(() => {                this.index = this.teamConfigFormData.teamConfigList.indexOf(item)                if (index !== -1) {                    this.teamConfigFormData.teamConfigList.splice(index, 1)                }            }).catch(() => {            });        },        //-------租户配置的methods-end-----------        getAppInfos() {            this.listLoading = true;            getAppInfos(this.getAppInfosParams).then(response => {                this.list = response.content.list;                this.total = response.content.total;                this.listLoading = false;            });        },        handleFilter() {            this.getAppInfosParams.page = 1;            this.getAppInfos();        },        modifyStatus(id, status) {            let tips;            let successTips;            let cancelTips;            if (status === 1) {                tips = '确认恢复?';                successTips = '恢复成功';                cancelTips = '恢复取消';            } else if (status === 0) {                tips = '确认删除?';                successTips = '删除成功';                cancelTips = '删除取消';            } else {                this.$notify({                    title: '警告',                    message: '未知状态',                    type: 'warning',                    duration: 2000                });                return;            }            this.$confirm(tips, 'Warning', {                confirmButtonText: '确认',                cancelButtonText: '取消',                type: 'warning'            }).then(() => {                updateAppInfo({id: id, status}).then(() => {                    this.$notify({                        title: '成功',                        message: successTips,                        type: 'success',                        duration: 2000                    });                    this.handleFilter();                });            }).catch(() => {                this.$message({                    type: 'info',                    message: cancelTips                });            });        },        handleCreate() {            this.initData();            this.addInitTeamConfig();            this.resetTemp(this.userName);            this.dialogStatus = this.dialogStatusMap.create.key;            this.dialogFormVisible = true;            this.$nextTick(() => {                this.$refs['dataForm'].clearValidate();            });        },        // 保存文件        saveApplication() {            console.log("wo 来到了 上传的方法-------")            // 多文件上传            let teamConfigListLength = this.teamConfigFormData.teamConfigList.length;            if (teamConfigListLength === 0) {                return;            }            // 本地环境的文件是默认的            if (process.env.NODE_ENV === 'development') {                for (let i = 0; i < teamConfigListLength; i++) {                    console.log("我是循环中的方法")                    console.log(process.env.NODE_ENV)                    this.teamConfigFormData.teamConfigList[i].icon = 'https://s3.cn-north-1.jdcloud-oss.com/eepaas-filecenter-pre/H9vSpvxDJQmtKXFqVSCmOic2y.png?response-content-disposition=filename%2A%3DUTF-8%27%2712.png&response-content-type=image%2Fpng&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20201022T080941Z&X-Amz-SignedHeaders=host&X-Amz-Expires=604800&X-Amz-Credential=CFDC5A51C7123F3EA1517CBC874410A6%2F20201022%2Fcn-north-1%2Fs3%2Faws4_request&X-Amz-Signature=d5c96567e8cf1a2a7bde5b749d2a6cbae6bbfa451675f93d6bf488339d2f1d10';                    // this.teamConfigFormData.teamConfigList[i].icon = 12345;                    this.teamConfigFormData.teamConfigList[i].iconFile = null;                }                console.log("----上传文件放回的 -总的  全的this.teamConfigFormData.teamConfigList---")                console.log(this.teamConfigFormData.teamConfigList)                this.createData();                return;            }            // 预发和生产的环境是真实上传的文件            for (let i = 0; i < teamConfigListLength; i++) {                let iconFile = this.teamConfigFormData.teamConfigList[i].iconFile;                if (!iconFile) {                    continue;                }                let data = new FormData();                data.append('appKey', process.env.VUE_APP_FILE_SERVICE_APP_KEY);                data.append('fileType', 'image/png');                data.append('needAuthn', '0');                data.append('file', iconFile);                console.log("-----let data = new FormData()-------");                console.log(data)                // 这是一个上传文件的通用方法,直接发回一个url                uploadFile(data).then((response) => {                    this.teamConfigFormData.teamConfigList[i].icon = getFileUrl(response.content.fileDownloadUrl);                    console.log("---------查看上传后的URL----------")                    console.log(this.teamConfigFormData.teamConfigList[i].icon)                    console.log("----上传文件放回的 -总的  全的---response----")                    console.log(response)                    console.log("----上传文件放回的 -总的  全的+++teamConfigList+++")                    console.log(this.teamConfigFormData.teamConfigList)                    this.teamConfigFormData.teamConfigList[i].iconFile = null;                });            }            this.createData();        },        /* 新增的方法 */        createData() {            this.$refs['dataForm'].validate((valid) => {                if (valid) {                    this.temp.id = undefined;                    // 执行 insert                    insertAppInfo(this.teamConfigFormData).then((response) => {                        console.log("-------------")                        console.log(response)                        /*this.dialogFormVisible = false;                        this.$notify({                            title: '成功',                            message: '创建成功',                            type: 'success',                            duration: 2000                        });*/                        // 刷新列表                        // this.handleFilter();                    });                }            });        },    }};script><style scoped>style><style>    /*  **********上传图片的样式**********  */    #smallCss .el-upload .el-upload-dragger {        width: 28px;        height: 28px;    }    .app-icon-uploader .el-upload .el-upload-dragger {        width: 28px;        height: 28px;    }style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值