el-upload上傳圖片

<template>
  <el-container>
    <div :class="{'hideAddBtn':fileList.length}">
      <el-upload
        :action="uploadImage"
        :headers="{ token:jdb_token }"
        :limit="1"
        :file-list="fileList"
        :on-exceed="handleExceed"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        accept=".jpg, .jpeg, .png, .gif, .bmp"
        list-type="picture-card"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
    </div>
  </el-container>
</template>

<script>
import searchArticle from "../../../api/searchArticle.js";
import { mapState } from "vuex";
export default {
  data() {
    return {
      fileList: [],
      uploadImage: process.env.VUE_APP_API + searchArticle.uploadImage
    };
  },
  computed: {
    ...mapState(["jdb_token"])
  },
  methods: {
    beforeUpload(file) {
      //上傳圖片前
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("圖片大小不能超過 2MB!");
      }
      return isLt2M;
    },
    handleSuccess(file, fileList) {
      //此處的fileList是個對象
      //上傳成功
      if (file.code === 200) {
        this.fileList.push(fileList);
      }
    },
    handleExceed() {
      //圖片超出上限
      this.$message.error("當前限制選擇 1 個文件");
    },
    handleRemove(file, fileList) {
      //移除圖片
      this.fileList = [];
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .hideAddBtn .el-upload--picture-card {
  display: none;
}
</style>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章