使用Element的upload上传图片及图片预览,删除等

1,446 阅读1分钟

在这里插入图片描述
代码中都有相关注释,其他属性可查看element官网

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>element上传图片</title>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>

<body>
  <div id='app'>
    <div>
      <div class='diatitle' style='margin: 10px 0'>图片上传</div>
      <el-upload :action="upurl" :data="myData" list-type="picture-card" :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove" :on-change='imgchange' :file-list="fileList" multiple>
        <i class="el-icon-plus"></i>
      </el-upload>

      <el-dialog :visible.sync="innerVisible" append-to-body>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>
  </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6/dist/vue.min.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
  var Vue = new Vue({
    el: '#app',
    data: {
      upurl: 'https://xxxx', //上传的地址
      myData: {key: 'Gn1xVdBiTClSSHKZifg0pTQSU5XGagWO'}, //上传时附带的额外参数
      fileList: [], //上传的文件列表
      dialogImageUrl: '',
      innerVisible: false,
    },
    created() {

    },
    methods: {
      //上传
      // on-change	文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
      imgchange(file, fileList) {
        this.fileList = fileList
        console.log('111', file, fileList, this.fileList)
      },
      //on-remove	文件列表移除文件时的钩子
      handleRemove(file, fileList) {
        this.fileList = fileList
        console.log(this.fileList)
      },
      //on-preview	点击文件列表中已上传的文件时的钩子(预览图片弹窗)
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.innerVisible = true;
      },
    }
  })
</script>

</html>