SImg.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <template>
  2. <div class="imgBox">
  3. <el-image v-show="showRaw" :src="rawImage" alt="21" class="baseImg"/>
  4. <img v-show="!showRaw" ref="showImg" src="" alt="" class="showImg"/>
  5. <input class="fileInput"
  6. type="file"
  7. accept="image/png, image/jpeg"
  8. ref="fileInput"
  9. @change="fileChangeHandle">
  10. <div class="closeBtn" @click="clearSelect">x</div>
  11. </div>
  12. </template>
  13. <script>
  14. export default {
  15. name: "ImgSelect",
  16. props:{
  17. rawImage:{default:''}
  18. },
  19. data(){
  20. return {
  21. //
  22. showRaw: true,
  23. }
  24. },
  25. mounted(){
  26. console.log(this.showRaw);
  27. },
  28. methods:{
  29. fileChangeHandle(){
  30. let files = this.$refs.fileInput.files;
  31. console.log(files);
  32. console.log('1234');
  33. let imgFile = files[0];
  34. if(!imgFile){
  35. this.showRaw = true;
  36. return this.$message.warning('未选择图片')}
  37. // 检查格式
  38. let imageTypeReg = /^image\//;
  39. if(!imageTypeReg.test(imgFile.type)){
  40. this.$refs.fileInput.files = null;
  41. this.showRaw = true;
  42. return this.$message.warning('未受支持的格式')
  43. }
  44. // 发送change事件
  45. this.$emit("imgChange",imgFile);
  46. this.showRaw = false;
  47. // 设置预览图
  48. this.$refs.showImg.file = imgFile;
  49. let reader = new FileReader();
  50. reader.onload = (function(aImg) {
  51. return function(e) { aImg.src = e.target.result; }; })
  52. (this.$refs.showImg);
  53. reader.readAsDataURL(imgFile);
  54. },
  55. clearSelect(){
  56. this.showRaw = true;
  57. this.$emit("imgChange")
  58. }
  59. }
  60. }
  61. </script>
  62. <style scoped>
  63. .imgBox{
  64. width: 100%;
  65. height: 100%;
  66. min-width: 50px;
  67. min-height: 50px;
  68. position: relative;
  69. display: flex;
  70. justify-content: center;
  71. box-shadow: 0 0 3px lightgray;
  72. }
  73. .imgBox .showImg,.fileInput,.baseImg{
  74. width: 100%;
  75. height: 100%;
  76. position: absolute;
  77. display: block;
  78. }
  79. .imgBox .fileInput{
  80. left: 0;
  81. top: 0;
  82. }
  83. .imgBox .showImg,.baseImg{
  84. height: 100%;
  85. width: auto;
  86. max-width: 100%;
  87. }
  88. .imgBox .fileInput{
  89. opacity: 0;
  90. }
  91. .imgBox .closeBtn{
  92. width: 25px;
  93. height: 25px;
  94. border-radius: 50%;
  95. display: flex;
  96. justify-content: center;
  97. align-items: center;
  98. position: absolute;
  99. right: 5px;
  100. top: 5px;
  101. color: red;
  102. cursor: pointer;
  103. box-shadow: 1px 1px 2px gray;
  104. }
  105. </style>