index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import api from '@/api'
  2. // 上传头像mixin
  3. export const avatarMixin = {
  4. data () {
  5. return {
  6. cropperOption: {
  7. visible: false,
  8. img: null
  9. }
  10. }
  11. },
  12. methods: {
  13. uploadImg (event) {
  14. let file = event.target.files[0]
  15. if (this.beforeAvatarUpload(file)) {
  16. this.readFileAsBlob(file)
  17. }
  18. },
  19. readFileAsBlob (file) {
  20. let self = this
  21. let reader = new FileReader()
  22. reader.readAsDataURL(file)
  23. reader.onload = e => {
  24. self.cropperOption.img = e.target.result
  25. self.cropperOption.visible = true
  26. }
  27. reader.onerror = () => {
  28. self.readFileAsBlob(file)
  29. }
  30. },
  31. cropperClose () {
  32. this.cropperOption.visible = false
  33. },
  34. cropperSubmit (image) {
  35. let param = new FormData()
  36. param.append('user_id', this.$store.state.userId)
  37. param.append('token', this.$store.state.token)
  38. param.append('cover_photo', image)
  39. if (this.isMe) {
  40. api.user.changePhoto(param).then(({ data }) => {
  41. if (data.code === 0) {
  42. this.handleAvatarSuccess(image)
  43. this.cropperClose()
  44. }
  45. })
  46. } else {
  47. param.append('group_id', this.$store.state.curSession)
  48. api.group.changeCover(param).then(({ data }) => {
  49. if (data.code === 0) {
  50. this.handleAvatarSuccess(image)
  51. this.cropperClose()
  52. }
  53. })
  54. }
  55. },
  56. handleAvatarSuccess (file) {
  57. let imageUrl = URL.createObjectURL(file)
  58. this.$showTips(this.$t('public.uploadSucc'))
  59. if (this.isMe) {
  60. // 用户头像
  61. this.$store.commit('updateUserPhoto', imageUrl)
  62. this.$store.commit('updateMemberAvatar', {
  63. userId: this.$store.state.userId,
  64. imageUrl: imageUrl
  65. })
  66. } else {
  67. // 群头像
  68. this.$store.dispatch('updateSessionItem', {
  69. sessionId: this.$store.state.curSession,
  70. data: {
  71. cover_photo: imageUrl
  72. }
  73. })
  74. this.$store.commit('updateGroup', {
  75. key: 'coverPhoto',
  76. data: imageUrl
  77. })
  78. console.log('群头像update')
  79. }
  80. },
  81. beforeAvatarUpload (file) {
  82. const isIMG = file.type.indexOf('image') > -1
  83. const isLt1M = file.size / 1024 / 1024 < 2
  84. if (!isIMG || !isLt1M) {
  85. this.$showTips(this.$t('userinfo.maxUploadTips'))
  86. }
  87. return isIMG && isLt1M
  88. }
  89. }
  90. }