完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<title>upload</title>
</head>
<body>
<div id="app">
<el-form :model="addForm" ref="addForm" :rules="rules">
<el-form-item label="图片" prop="fileList" width="100px">
<el-upload
drag
action="#"
:auto-upload="false"
:limit="length"
:on-exceed="overLimit"
:on-remove="removeFile"
:before-remove="beforeRemoveFile"
:on-change="changeFileList"
accept=".jpg,jpeg,png"
:on-preview="previewFile"
multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</el-form-item>
</el-form>
</div>
</body>
</html>
<script>
new Vue({
el: "#app",
data() {
return {
length: 3,
addForm:{
fileList:[],
},
rules:{
fileList:[{
required:true,message:"图片列表不能为空"
}]
}
}
},
methods: {
// 超出limit钩子
overLimit(files, fileList) {
this.$message.warning(`上传文件数:${files.length}加上当前已上传的文件列表数:${fileList.length},超过最大上传数:${this.length}`)
},
//删除文件列表中的文件之后钩子
removeFile(file, fileList) {
this.addForm.fileList = fileList;
this.$refs.addForm.validateField("fileList")
this.$message.success(`成功删除${file.raw.name},剩余文件数为:${fileList.length}`)
},
//删除文件列表中的文件之前钩子
beforeRemoveFile(file, fileList) {
return this.$confirm(`确定删除${file.raw.name}吗?`)
},
//点击文件列表的文件钩子
previewFile(file){
this.$message.success(`点击文件${file.raw.name}`)
},
//添加文件成功后钩子(选中n个文件添加时,该方法调用n次)
changeFileList(file,fileList){
this.addForm.fileList = fileList;
this.$refs.addForm.validateField("fileList")
}
}
})
</script>
效果图
初始图
文件非空校验图
个人心得
- accpet可以过滤要添加的文件类型
- on-remove是删除文件列表钩子,参数一是删除的文件,参数二是剩余的文件列表
- on-change是添加文件成功钩子,参数一是添加的文件,参数二是文件列表+添加的文件,注意,在多文件添加时,此方法会执行多次
- on-exceed是超出最大文件上传数钩子,参数一是添加的文件列表,参数二是当前已添加的文件列表
- limit限制文件的添加数目
- drag是支持拖拽的方式添加文件,同时生成指定的样式边框
- action是指定上传的服务器路径
- auto-upload是指是否自动上传至服务器(我所做的项目不会上传到指定的服务器,而是用后端代码保存至服务器指定位置)
- before-remove是删除文件列表之前钩子,参数一是待删除的文件,参数二是未删除的文件列表
- on-preview是文件列表的文件预览点击钩子
- on-success,on-error,on-progress和before-upload都是上传文件服务器前后触发的钩子,暂时用不到,不花费时间学
- 校验文件非空,不能像el-input文件框这样,prop配合v-model可以自动的校验,需要借助on-change和on-remove这两个钩子实现校验,通过this.$refs.xxx.validateField(“xx”),实现对this.x.xx属性的校验。