功能描述:

添加图片

上传成功在表格内显示该图片

点击编辑,打开上传图片对话框,图片回显(与添加共用同一个对话框)

html代码:(具体添加、编辑按钮以及表格内显示上传成功的图片html代码就不放了,这里只展示upload组件相关代码)

<el-upload ref="ref1"
           action=""
           :file-list="fileList"
           list-type="picture-card"
           accept="image/*"
           :auto-upload="false"
           :multiple="false"
           :limit="1">
  <i class="el-icon-plus"></i>
</el-upload>
<el-button type="primary"@click="dialogConfirm">确定</el-button>

官网el-upload参数说明(这里只放了现用到的参数):

参数说明类型可选值默认值
action必选参数,上传的地址string
multiple是否支持多选文件boolean
accept接受上传的文件类型(thumbnail-mode 模式下此参数无效)string
list-type文件列表的类型stringtext/picture/picture-cardtext
auto-upload是否在选取文件后立即进行上传booleantrue
file-list上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]array[]
limit最大允许上传个数number

js代码:

<script>
  export default {
    data() {
      return {
        filelist:[]
        dialogMode:'create'//create、edit
      };
    },
    methods: {
      fillFormData(){
          let formData = new FormData();
          let photo = this.$refs['ref1'].uploadFiles[0];
          if(photo===undefined){
            this.$message.error("请选择照片");
            return false;
          }
          if(photo!==undefined){
            formData.append('照片', photo.raw);//根据后端需要的参数进行相应更改,大多是文件格式
          }
          return formData;
        },

      dialogConfirm() {
          let formData=this.fillFormData();
          if(this.dialogMode ==='edit'){//dialogMode用于判断当前时添加还是编辑
            this.api.update(formData).then(res => {//调用修改接口
              if (res.data.code == "OK") {
                this.$message({
                  type: "success",
                  message: "修改成功!",
                  duration:5000
                });
                this.fileList=[];
              } else {
                this.$message.error(res.data.message);
              }
            },()=>{
              this.$message.error("修改失败");
            }).finally(()=>{
            });
          }else{
            this.api.insert(formData).then(res => {//添加接口
              if (res.data.code == "OK") {
                this.$message({
                  type: "success",
                  message: "新建成功!",
                  duration:5000
                });
                this.fileList=[];
              } else {
                this.$message.error(res.data.message);
              }
            },()=>{
              this.$message.error("新建失败");
            }).finally(()=>{
            });
          }
        }
    },
    //点击编辑时图片回显
    edit(info){//info=>后台接口返回的数据 
      let url=this.baseUrl+info.photo//url的地址根据项目实际需要,info.photo=>图片路径,this.baseUrl=>上传的网络地址
      this.fileList=[];
        this.fileList.push({
          'url': url   
        })
      this.dialogMode='edit';//设置为编辑
    },
    onCreateNew(){
      this.fileList=[];
      this.dialogMode='create';//设置为添加
    },
   }
  }
</script>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐