vue element-ui 常用事件方法

1. 前提

已安装elementUI并正确引入

2. 参数说明

参数 说明
:action 是执行上传动作的后台接口,本文置空采用http-request取而代之拦截请求,进行文件上传
:multiple="true" 设置是否可以同时选中多个文件上传,这个也是<input type='file'>的属性
:limit="1" 上传文件数量,设置最多可以上传的文件数量,超出此数量后选择的文件是不会被上传的。
:on-exceed 绑定的方法则是处理文件超出限制数量后的动作
:file-list="fileList" 用于显示已上传文件列表,其中fileList是数组对象,初始为空。
参数 说明
accept="image/jpeg,image/gif,image/png" 限制上传文件的格式

具体可参考HTML5 input file类型,accept(文件类型控制)

  • 这个是直接使用<input type='file'>一样的属性了,accept属性的值可以是accept="image/gif, image/jpeg, text/plain, application/pdf"等等.
  • 添加了accept属性仅仅是选择文件时限制格式,其实用户还是可以点选“所有文件”选项,上传其他格式。
  • 如果需要在上传时校验文件格式,则需要在:before-uploadon-change这个钩子绑定相应的方法来校验,具体校验方法查看3. 页面中使用中的beforeUploadhandleChange方法
参数 说明
abort 取消上传请求

this.$refs.upload.abort( file);/ /这里的file为fileList 中的 file 对象
参数 说明
slot="tip 用于添加提示如正确的文件格式应该为***,如

<div slot="tip" class="el-upload__tip">请上传图片格式文件</div>
参数 说明
abort 取消上传请求

this.$refs.upload.abort( file);/ /这里的file为fileList 中的 file 对象

其他参数具体参考
elementUI官方API文档>upload

3. 页面中使用

  • template

<template>
    <el-upload
        :class="{disabled:preview||fileIds.length===1}"
        ref="upload"
        action
        list-type="picture-card"
        :file-list="fileList"
        :disabled="preview"
        accept="image/jpeg,image/gif,image/png"
        :multiple="true"
        :limit="1"
        :auto-upload="true"
        :on-preview="handlePictureCardPreview"
        :before-remove="beforeRemove"
        :http-request="getUploadFile"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        :on-change="handleChange"
        :on-progress="onProgress"
        :on-error="handleError"
        :on-exceed="handleExceed"
    >
        <!-- 触发上传的按钮 -->
        <i class="el-icon-plus"></i>
        <div slot="tip" class="el-upload__tip">请上传图片格式文件</div>
    </el-upload>
</template>
  • script

<script>
export default {
    data() {
        return {   
            /* 文件上传区 */
            fileList: [], // 文件列表
            isValidUpload: true, // 图片是否符合要求
            delFileUid: '', // 待删除的图片uid
            dialogImageUrl: '', // 预览的图片地址
            dialogVisible: false, // 是否显示-预览图片
            fileObj: {}, // 待上传文件
            fileIds: [], // 存放文件uid与后台传过来的id
            imgId: [] // 需要上传的后端返回的文件ID
        };
    },
    methods:{
        // --------------------el-upload上传文件-开始--------------------
        // 图片预览-on-preview-事件
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        // 文件上传
        // autoUpload

        // 文件上传-on-exceed-事件-文件超出个数限制时的钩子
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 5 个文件,请重新选择`);
        },

          // 文件上传-on-change-事件-文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
        handleChange(file, fileList) {
            // console.log('handleChange>', 'file', file, 'fileList', fileList);
            // console.log('file.type', file.raw.type);
            const isPNG = file.raw.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            let errMsg = '';
            if (!isPNG) {
                errMsg = '上传图片只能是 JPG 格式!';
                // this.$message.error('上传图片只能是 JPG 格式!');
                fileList = fileList.pop();
            } else if (!isLt2M) {
                errMsg = '上传图片大小不能超过 2MB!';
                // this.$message.error('上传图片大小不能超过 2MB!');
                fileList = fileList.pop();
            }
            this.isValidUpload = isPNG && isLt2M;
            if (!this.isValidUpload) {
                this.$confirm(`${errMsg}`, '系統提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    showCancelButton: false,
                    customClass: 'confirm-success',
                    type: 'error'
                })
                    .then(() => {
                        //
                    })
                    .catch(() => {
                        //
                    });
            }
            return this.isValidUpload;
        },

        // 文件上传-before-upload-事件-文件上传前
        beforeUpload(file) {
            // console.log('beforeUpload>', 'file', file);
            this.fileObj = new FormData();
            this.fileObj.append('file', file, file.name);
            console.log('beforeUpload>', 'file', file, 'fileObj', this.fileObj);
            if (file.type.split('/')[0] === 'image') {
                let _this = this;
                let reader = new FileReader();
                // let fileNew = event.target.files[0];// 写在beforupload时注释掉此行,在handleChange中时取消此行的注释
                reader.readAsDataURL(file);
                reader.onload = function(theFile) {
                    let image = new Image();
                    image.src = theFile.target.result;
                    image.onload = function() {
                        if (!_this.creativeSize(this.width, this.height)) {
                            _this.$message.info(
                                `${file.name}尺寸为${this.width}*${this.height},图片最佳比例为 560 * 670 !`
                            );
                            file.width = this.width;
                            file.height = this.height;
                            console.log(file.width, file.height);
                        } else {
                            file.width = this.width;
                            file.height = this.height;
                            console.log(file.width, file.height);
                        }
                    };
                };
            };
        },

        // 方法-计算图片比例是否符合要求
        creativeSize(width, height) {
            let minWidth = 560;
            let minHeight = 670;
            let isCreativeSize = true;
            if (width * minHeight > height * minWidth) {
                isCreativeSize =
                    width - Math.ceil((height * minWidth) / minHeight) < 2;
            } else {
                isCreativeSize =
                    height - Math.ceil((width * minHeight) / minWidth) < 2;
            }

            if (width < minWidth || height < minHeight) {
                // this.$message.error(`像素不够`);
                return false;
            } else if (isCreativeSize) {
                return true;
            } else {
                return false;
            }
        },

        // 文件上传-http-request-事件-拦截请求
        getUploadFile(fileObj) {
            // console.log('getUploadFile>', 'fileObj', fileObj);
            // 上传图片
            if (this.isValidUpload) {
                // 请求接口-上传图片
                this.uploadFile(this.fileObj).then(res => {
                    // console.log('uploadFile', res);
                    if (res.code === 1) {
                        this.fileIds.push({
                            uid: fileObj.file.uid,
                            imgId: res.data
                        });
                    }
                    // console.log('uploadFile>','fileIds', this.fileIds);
                });
            }
        },

        // 文件上传-on-progress-事件
        onProgress(event, file, fileList) {
            // console.log('onProgress', response, file, fileList);
        },

        // 文件上传-before-remove-事件-移除文件前
        beforeRemove(file, fileList) {
            // console.log('beforeRemove>','file', file);
            return this.$confirm(`确定移除 ${file.name}?`);
        },

        // 文件上传-on-remove-事件-移除文件后
        handleRemove(file, fileList) {
            for (let i = 0; i < this.fileIds.length; i++) {
                if (this.fileIds[i].uid === file.uid) {
                    if (!this.delFileUid) {
                        this.delFileUid = this.fileIds[i].imgId;
                    } else {
                        this.delFileUid =
                            `${this.delFileUid},` + this.fileIds[i].imgId;
                    }
                    this.fileIds.splice(i, 1);
                }
            }
            // console.log('handleRemove>', 'delFileUid', this.delFileUid);
            let params = {
                id: this.delFileUid
            };
            this.delsData(params);
        },

        // 接口-删除文件
        delsData(params) {
            if (this.delFileUid) {
                this.dels({ ids: this.delFileUid }).then(res => {
                    // console.log('dels', res);
                    this.delFileUid = '';
                    console.log('delsData>', 'delFileUid', this.delFileUid);
                });
            }
        },

        // 文件上传-on-error-事件
        handleError(err, file, fileList) {
            console.log('handleError', err, file, fileList);
        },
       
        // --------------------el-upload上传文件-结束-------------------- *

        // 表单提交
        submit(formName) {
            console.log('ruleForm',this.ruleForm);
            this.$refs[formName].validate(valid => {
                if (valid) {
                    console.log('submit');
                    let imgId = [];
                    for (let i = 0; i < this.fileIds.length; i++) {
                        imgId.push(this.fileIds[i].imgId);
                    }
                    let params = {
                        name: this.ruleForm.name,
                        fileIds: imgId
                    };
                    // 提交接口
                    this.interfaceName(params)
                        .then(res => {
                            console.log(res);
                            if (res.code === 1) {
                                this.$confirm(`提交成功`, '系統提示', {
                                    confirmButtonText: '确定',
                                    cancelButtonText: '取消',
                                    showCancelButton: false,
                                    customClass: 'confirm-success',
                                    type: 'success'
                                })
                                    .then(() => {
                                        this.$router.push('');
                                    })
                                    .catch(() => {
                                        // this.$message.info('已取消');
                                    });
                            } else {
                                // this.$message.error(res.msg);
                            }
                            this.fileIds = [];// 清除待文件序列
                            this.resetFormDetail();
                            this.$refs.upload.clearFiles();// 清除上传列表
                        })
                        .catch(err => {
                            console.log(err);
                        });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        // 方法-重置表单
        resetFormDetail() {
            this.formDetail.name = '';
        },
    }
}
</script>

二、input等的change事件中传递自定义参数


通过鼠标或键盘输入字符

Input 为受控组件,它总会显示 Vue 绑定值。
通常情况下,应当处理 input 事件,并更新组件的绑定值(或使用v-model)。否则,输入框内显示的值将不会改变。
不支持 v-model 修饰符。

一、无效写法

@change="doSomething(val, index)"

<div v-for="(item,index) in itemList">
   <el-input v-model="item.value" @change="doSomething(val, index)"> </el-input >
</div>

二、有效写法

@change="((val)=>{changeStatus(val, index)})"

<div v-for="(item,index) in itemList">
   <el-input v-model="item.value" @change="((val)=>{doSomething(val, index)})"> </el-input>
 </div>


https://www.jianshu.com/p/3401d353eda4。

猜你喜欢

转载自blog.csdn.net/Yilong18/article/details/128243441