upload.vue 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <template>
  2. <div id="upload">
  3. <el-upload
  4. v-if="url"
  5. ref="upload"
  6. :action="url"
  7. :list-type="listType"
  8. :file-list="fileList"
  9. :limit="limit"
  10. :on-exceed="outLimit"
  11. :on-preview="handlePictureCardPreview"
  12. :before-remove="handleRemove"
  13. :on-success="onSuccess"
  14. :show-file-list="showList"
  15. :accept="accept"
  16. >
  17. <el-button size="small" type="primary" v-if="isBtn">点击上传</el-button>
  18. <template v-else>
  19. <i class="el-icon-plus"></i>
  20. </template>
  21. <template #tip v-if="tip">
  22. {{ tip }}
  23. </template>
  24. </el-upload>
  25. <el-dialog :visible.sync="dialogVisible">
  26. <img width="100%" :src="dialogImageUrl" alt="" />
  27. </el-dialog>
  28. </div>
  29. </template>
  30. <script>
  31. import _ from 'lodash';
  32. export default {
  33. name: 'upload',
  34. props: {
  35. url: { type: null },
  36. limit: { type: Number },
  37. data: { type: null },
  38. type: { type: String },
  39. isBtn: { type: Boolean, default: false },
  40. showList: { type: Boolean, default: true },
  41. accept: { type: String },
  42. tip: { type: String, default: undefined },
  43. listType: { type: String, default: 'picture-card' },
  44. },
  45. components: {},
  46. data: () => ({
  47. dialogVisible: false,
  48. dialogImageUrl: '',
  49. fileList: [],
  50. }),
  51. created() {
  52. if (this.data) {
  53. this.defalutProcess(this.data);
  54. }
  55. },
  56. watch: {
  57. data: {
  58. handler(val) {
  59. this.defalutProcess(val);
  60. },
  61. },
  62. },
  63. computed: {},
  64. methods: {
  65. handlePictureCardPreview(file) {
  66. this.dialogImageUrl = file.url;
  67. this.dialogVisible = true;
  68. },
  69. handleRemove(file) {
  70. return true;
  71. },
  72. outLimit() {
  73. this.$message.error('只允许上传1个文件');
  74. },
  75. onSuccess(response, file, fileList) {
  76. //将文件整理好传回父组件
  77. this.$emit('upload', { type: this.type, data: response });
  78. },
  79. defalutProcess(val) {
  80. if (typeof val === 'object' && _.get(val, length) !== undefined && val.length > 0) {
  81. let newArr = [];
  82. val.map(item => {
  83. let object = {};
  84. object.name = item.name;
  85. object.url = `${item.uri}`;
  86. newArr.push(object);
  87. });
  88. this.$set(this, `fileList`, newArr);
  89. } else if (typeof val === 'object' && _.get(val, length) === undefined) {
  90. let object = {};
  91. object.name = val.name;
  92. object.url = `${val.uri}`;
  93. this.$set(this, `fileList`, [object]);
  94. } else if (typeof val === 'string') {
  95. this.$set(this, `fileList`, [{ name: '附件', url: val }]);
  96. }
  97. },
  98. },
  99. };
  100. </script>
  101. <style lang="less" scoped></style>