ImgsUpload.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <template>
  2. <view class="imageUpload">
  3. <view class="images-box" @click="handlerUploadImg" v-if="fileList.length">
  4. <image class="upd-img" v-for="(item, index) of fileList" :key="index" :src="item" mode="aspectFill"></image>
  5. </view>
  6. <view class="images-box" @click="handlerUploadImg" v-else>
  7. <image src="/static/upload.jpg" mode="aspectFill"></image>
  8. </view>
  9. </view>
  10. </template>
  11. <script>
  12. export default {
  13. props: {
  14. value: {
  15. type: String,
  16. default: '',
  17. },
  18. imageList: {
  19. type: String,
  20. default: ""
  21. }
  22. },
  23. data() {
  24. return {
  25. uploadCount: 0,
  26. fileList: [],
  27. };
  28. },
  29. onLoad(option) {},
  30. onShow() {
  31. },
  32. mounted() {
  33. this.fileList = this.imageList.split(',')
  34. },
  35. created() {},
  36. methods: {
  37. // 上传头像
  38. async handlerUploadImg() {
  39. try {
  40. const res = await uni.showActionSheet({
  41. itemList: ['拍照', '从相册选择'],
  42. });
  43. if (res.tapIndex === 0) {
  44. // 用户选择拍照
  45. this.takePhoto();
  46. } else if (res.tapIndex === 1) {
  47. // 用户选择从相册选择
  48. this.chooseImage();
  49. }
  50. } catch (error) {
  51. console.error(error);
  52. }
  53. },
  54. // 拍照
  55. takePhoto() {
  56. uni.chooseImage({
  57. sourceType: ['camera'],
  58. count: 1 - this.uploadCount,
  59. success: res => {
  60. const tempFilePaths = res.tempFilePaths;
  61. // 调用上传图片的方法
  62. tempFilePaths.map(rs => {
  63. this.uploadAvatar(rs);
  64. });
  65. },
  66. fail: error => {
  67. console.error(error);
  68. },
  69. });
  70. },
  71. //从相册中选择
  72. chooseImage() {
  73. uni.chooseImage({
  74. sourceType: ['album'],
  75. count: 9 - this.uploadCount,
  76. success: res => {
  77. const tempFilePaths = res.tempFilePaths;
  78. tempFilePaths.map(rs => {
  79. this.uploadAvatar(rs);
  80. });
  81. // 调用上传图片的方法
  82. },
  83. fail: error => {
  84. console.error(error);
  85. },
  86. });
  87. },
  88. // 上传头像
  89. uploadAvatar(filePath) {
  90. // 在这里实现上传头像的逻辑,将filePath作为参数传入
  91. this.fileList.push(filePath);
  92. this.uploadCount = this.fileList.length;
  93. // 手动触发组件的重新渲染
  94. this.$forceUpdate();
  95. this.$emit('update', this.fileList, this.value);
  96. },
  97. },
  98. };
  99. </script>
  100. <style lang="scss" scoped>
  101. .imageUpload {
  102. .images-box {
  103. width: 100%;
  104. height: 400rpx;
  105. background-color: pink;
  106. image {
  107. height: 100%;
  108. width: 100%;
  109. }
  110. }
  111. }
  112. </style>