index.vue 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. <template>
  2. <div class="component-upload-image">
  3. <el-upload
  4. multiple
  5. :disabled="disabled"
  6. :action="uploadImgUrl"
  7. list-type="picture-card"
  8. :on-success="handleUploadSuccess"
  9. :before-upload="handleBeforeUpload"
  10. :data="data"
  11. :limit="limit"
  12. :on-error="handleUploadError"
  13. :on-exceed="handleExceed"
  14. ref="imageUpload"
  15. :on-remove="handleDelete"
  16. :show-file-list="true"
  17. :headers="headers"
  18. :file-list="fileList"
  19. :on-preview="handlePictureCardPreview"
  20. :class="{hide: this.fileList.length >= this.limit}"
  21. >
  22. <i class="el-icon-plus"></i>
  23. </el-upload>
  24. <!-- 上传提示 -->
  25. <div class="el-upload__tip" slot="tip" v-if="showTip && !disabled">
  26. 请上传
  27. <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
  28. <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
  29. 的文件
  30. </div>
  31. <el-dialog
  32. :visible.sync="dialogVisible"
  33. title="预览"
  34. width="800"
  35. append-to-body
  36. >
  37. <img
  38. :src="dialogImageUrl"
  39. style="display: block; max-width: 100%; margin: 0 auto"
  40. />
  41. </el-dialog>
  42. </div>
  43. </template>
  44. <script>
  45. import { getToken } from "@/utils/auth"
  46. import Sortable from 'sortablejs'
  47. export default {
  48. props: {
  49. value: [String, Object, Array],
  50. // 上传接口地址
  51. action: {
  52. type: String,
  53. default: "/file/upload"
  54. },
  55. // 上传携带的参数
  56. data: {
  57. type: Object
  58. },
  59. // 图片数量限制
  60. limit: {
  61. type: Number,
  62. default: 5
  63. },
  64. // 大小限制(MB)
  65. fileSize: {
  66. type: Number,
  67. default: 5
  68. },
  69. // 文件类型, 例如['png', 'jpg', 'jpeg']
  70. fileType: {
  71. type: Array,
  72. default: () => ["png", "jpg", "jpeg"]
  73. },
  74. // 是否显示提示
  75. isShowTip: {
  76. type: Boolean,
  77. default: true
  78. },
  79. // 禁用组件(仅查看图片)
  80. disabled: {
  81. type: Boolean,
  82. default: false
  83. },
  84. // 拖动排序
  85. drag: {
  86. type: Boolean,
  87. default: true
  88. }
  89. },
  90. data() {
  91. return {
  92. number: 0,
  93. uploadList: [],
  94. dialogImageUrl: "",
  95. dialogVisible: false,
  96. hideUpload: false,
  97. uploadImgUrl: process.env.VUE_APP_BASE_API + this.action, // 上传的图片服务器地址
  98. headers: {
  99. Authorization: "Bearer " + getToken(),
  100. },
  101. fileList: []
  102. }
  103. },
  104. mounted() {
  105. if (this.drag && !this.disabled) {
  106. this.$nextTick(() => {
  107. const element = this.$refs.imageUpload?.$el?.querySelector('.el-upload-list')
  108. Sortable.create(element, {
  109. onEnd: (evt) => {
  110. const movedItem = this.fileList.splice(evt.oldIndex, 1)[0]
  111. this.fileList.splice(evt.newIndex, 0, movedItem)
  112. this.$emit("input", this.listToString(this.fileList))
  113. }
  114. })
  115. })
  116. }
  117. },
  118. watch: {
  119. value: {
  120. handler(val) {
  121. if (val) {
  122. // 首先将值转为数组
  123. const list = Array.isArray(val) ? val : this.value.split(',')
  124. // 然后将数组转为对象数组
  125. this.fileList = list.map(item => {
  126. if (typeof item === "string") {
  127. item = { name: item, url: item }
  128. }
  129. return item
  130. })
  131. } else {
  132. this.fileList = []
  133. return []
  134. }
  135. },
  136. deep: true,
  137. immediate: true
  138. }
  139. },
  140. computed: {
  141. // 是否显示提示
  142. showTip() {
  143. return this.isShowTip && (this.fileType || this.fileSize)
  144. },
  145. },
  146. methods: {
  147. // 上传前loading加载
  148. handleBeforeUpload(file) {
  149. let isImg = false
  150. if (this.fileType.length) {
  151. let fileExtension = ""
  152. if (file.name.lastIndexOf(".") > -1) {
  153. fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1)
  154. }
  155. isImg = this.fileType.some(type => {
  156. if (file.type.indexOf(type) > -1) return true
  157. if (fileExtension && fileExtension.indexOf(type) > -1) return true
  158. return false
  159. })
  160. } else {
  161. isImg = file.type.indexOf("image") > -1
  162. }
  163. if (!isImg) {
  164. this.$modal.msgError(`文件格式不正确,请上传${this.fileType.join("/")}图片格式文件!`)
  165. return false
  166. }
  167. if (file.name.includes(',')) {
  168. this.$modal.msgError('文件名不正确,不能包含英文逗号!')
  169. return false
  170. }
  171. if (this.fileSize) {
  172. const isLt = file.size / 1024 / 1024 < this.fileSize
  173. if (!isLt) {
  174. this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`)
  175. return false
  176. }
  177. }
  178. this.$modal.loading("正在上传图片,请稍候...")
  179. this.number++
  180. },
  181. // 文件个数超出
  182. handleExceed() {
  183. this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`)
  184. },
  185. // 上传成功回调
  186. handleUploadSuccess(res, file) {
  187. if (res.code === 200) {
  188. this.uploadList.push({ name: res.data.url, url: res.data.url })
  189. this.uploadedSuccessfully()
  190. } else {
  191. this.number--
  192. this.$modal.closeLoading()
  193. this.$modal.msgError(res.msg)
  194. this.$refs.imageUpload.handleRemove(file)
  195. this.uploadedSuccessfully()
  196. }
  197. },
  198. // 删除图片
  199. handleDelete(file) {
  200. const findex = this.fileList.map(f => f.name).indexOf(file.name)
  201. if (findex > -1) {
  202. this.fileList.splice(findex, 1)
  203. this.$emit("input", this.listToString(this.fileList))
  204. }
  205. },
  206. // 上传失败
  207. handleUploadError() {
  208. this.$modal.msgError("上传图片失败,请重试")
  209. this.$modal.closeLoading()
  210. },
  211. // 上传结束处理
  212. uploadedSuccessfully() {
  213. if (this.number > 0 && this.uploadList.length === this.number) {
  214. this.fileList = this.fileList.concat(this.uploadList)
  215. this.uploadList = []
  216. this.number = 0
  217. this.$emit("input", this.listToString(this.fileList))
  218. this.$modal.closeLoading()
  219. }
  220. },
  221. // 预览
  222. handlePictureCardPreview(file) {
  223. this.dialogImageUrl = file.url
  224. this.dialogVisible = true
  225. },
  226. // 对象转成指定字符串分隔
  227. listToString(list, separator) {
  228. let strs = ""
  229. separator = separator || ","
  230. for (let i in list) {
  231. if (list[i].url) {
  232. strs += list[i].url.replace(this.baseUrl, "") + separator
  233. }
  234. }
  235. return strs != '' ? strs.substr(0, strs.length - 1) : ''
  236. }
  237. }
  238. }
  239. </script>
  240. <style scoped lang="scss">
  241. // .el-upload--picture-card 控制加号部分
  242. ::v-deep.hide .el-upload--picture-card {
  243. display: none;
  244. }
  245. ::v-deep .el-upload-list--picture-card.is-disabled + .el-upload--picture-card {
  246. display: none !important;
  247. }
  248. // 去掉动画效果
  249. ::v-deep .el-list-enter-active,
  250. ::v-deep .el-list-leave-active {
  251. transition: all 0s;
  252. }
  253. ::v-deep .el-list-enter, .el-list-leave-active {
  254. opacity: 0;
  255. transform: translateY(0);
  256. }
  257. </style>