<template>
  <div>
    <div class="base-image" @click="upload">
      <i v-if="!base64Data" class="el-icon-plus"></i>
      <img v-else :src="base64Data" alt="">
      <input id="fileUpload" type="file" accept="image/png,image/jpg,image/jpeg" @change="handleFileChange" />
    </div>
    <span style="font-size: 12px;color:#ccc;">仅支持png，jpg，jpeg，大小限制为10kb</span>
  </div>
</template>

<script>
export default {
  name: "baseImage",
  data() {
    return {
      base64Data: null,
    };
  },
  props: {
    value: {
      type: String,
      default: '',
    }
  },
  watch:{
    value:{
      handler(v){
        if(!v) return;
        this.base64Data = v;
      },
      immediate:true
    }
  },
  methods:{
    upload(){
      let el = document.getElementById('fileUpload');
      el.click();
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      //console.log(file,file.type != 'image/png','file')
      //if(file.type != 'image/png' || file.type != 'image/jpg' || file.type != 'image/jpeg') return this.$message.warning('文件类型错误');
      if(file.size > 1024 * 10) return this.$message.warning('图标限制大小10kb')
      if (file) {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.base64Data = reader.result;
          this.$emit('change',reader.result)
        };
      }
    },
  },
  model:{
    props:'value',
    event:'change'
  }
}
</script>

<style lang="scss" scoped>
.base-image{
  width: 100px;
  height: 100px;
  border: 1px solid #eaeaea;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  >input{
    display: none;
  }
  >i{
    font-size: 30px;
    color:#f1f1f1;
  }
  >img{
    width: 100%;
    height: 100%;
  }
  &:hover{
    border: 1px solid #6ab7e1;
    >i{
      color:#eaeaea;
    }
  }
}
</style>
