上传图片组件的封装

1.图片上传组件

<template>
  <div style="display: inline-block;margin-bottom: 24px;position: relative">
    <input
      style="opacity: 0;width: 0;height: 0;position: absolute;"
      type="file"
      accept="image/png, image/jpg, image/jpeg"
      :id="fileInputId"
    />
    <Button
      :loading="loading.upload"
      v-if="!readPath"
      style="height: 150px;width: 150px;padding: 0;"
      type="dashed"
      @click="showSelect"
    >
      <div>
        <Icon type="md-add" />
      </div>
      <div>上传</div>
    </Button>
    <Button
      v-if="readPath"
      style="padding: 0;height: 150px;width: 150px;"
      type="dashed"
      @click="showImg"
    >
      <img height="145" width="145" :src="readPath" alt />
    </Button>
    <Modal v-model="modal" width="800">
      <div slot="header">
        <div style="height: 48px;">
          <Button :loading="loading.upload" @click="showSelect" type="primary">重新上传</Button>
        </div>
      </div>
      <div style="width: 800px;margin: -16px;">
        <img width="800" alt :src="readPath" />
      </div>
      <div slot="footer"></div>
    </Modal>
    <div class="subtitle">{{ subtitle }}</div>
  </div>
</template>

<script>
export default {
  name: "uploadImg",
  props: {
    fileInputId: {
      type: String,
      required: true
    },
    url: {
      type: String,
      required: false,
      default: ""
    },
    subtitle: {
      type: String,
      required: false,
      default: "支持格式:PNG、JPG、JPEG,建议图片尺寸64*64"
    }
  },
  data() {
    return {
      modal: false,
      readPath: "",
      loading: {
        upload: false
      }
    };
  },
  watch: {
    url(n) {
      this.readPath = n;
    }
  },
  methods: {
    showImg() {
      this.modal = true;
    },
    showSelect() {
      const self = this;
      const fileD = document.getElementById(self.fileInputId);
      fileD.click();
      fileD.onchange = function() {
        const fileObj = this;
        if (fileObj.files.length === 0) {
          return null;
        } else {
          const form = new FormData();
          form.append("file", fileObj.files[0]);
          self.loading.upload = true;
          self
            .$post("/upload/image", form)
            .then(res => {
              if (res.code == 0) {
                self.$emit("url", res.data[0]);
                self.readPath = res.data[0];
              }
            })
            .finally(() => {
              self.loading.upload = false;
            });
        }
      };
    }
  }
};
</script>

<style scoped>
.subtitle {
  width: 600px;
  position: absolute;
  color: #999;
}
</style>
  1. 页面中导入图片上传组件并注册
 import uploadImg from "@/components/component/uploadImg";
 export default {
 	component:{uploadImg }
 }
  1. 页面视图中使用
<uploadImg :url="obj1.icon" @url="obj1.icon = $event" :fileInputId="'photo'"></uploadImg>
  1. 效果

上传图片组件的封装_第1张图片

你可能感兴趣的:(vue)