imagePicker.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // components/imagePicker/imagePicker.js
  2. Component({
  3. /**
  4. * 组件的属性列表
  5. */
  6. properties: {
  7. images: Array,
  8. max: Number,
  9. imageWidth: Number,
  10. imageHeight: Number,
  11. readonly: Boolean
  12. },
  13. /**
  14. * 组件的初始数据
  15. */
  16. data: {
  17. imageMargin: 0
  18. },
  19. observers: {
  20. 'images, max, readonly': function (images, max, readonly) {
  21. this.setData({
  22. imageMargin: images.length + (images.length < max && !readonly) > 1 ? 5 : 0
  23. })
  24. }
  25. },
  26. /**
  27. * 组件的方法列表
  28. */
  29. methods: {
  30. chooseImage: function (num, callback) {
  31. wx.chooseImage({
  32. count: num,
  33. sizeType: ['original'],
  34. sourceType: ['album'],
  35. success: function (res) {
  36. callback(res.tempFilePaths)
  37. }.bind(this)
  38. })
  39. },
  40. previewImage: function (e) {
  41. wx.previewImage({
  42. urls: this.data.images,
  43. current: e.currentTarget.dataset.url
  44. })
  45. },
  46. removeImage: function (e) {
  47. for (var i = 0; i < this.properties.images.length; i++) {
  48. if (this.properties.images[i] == e.currentTarget.dataset.url) {
  49. var arr = this.properties.images
  50. arr.splice(i, 1)
  51. this.setData({
  52. images: arr
  53. })
  54. this.triggerEvent("change", {
  55. images: this.properties.images
  56. })
  57. break
  58. }
  59. }
  60. },
  61. addImage: function () {
  62. if (this.properties.images.length >= this.properties.max) {
  63. return
  64. }
  65. this.chooseImage(this.properties.max - this.properties.images.length, (img) => {
  66. var arr = this.properties.images.concat(img)
  67. this.setData({
  68. images: arr
  69. })
  70. this.triggerEvent("change", {
  71. images: this.properties.images
  72. })
  73. })
  74. },
  75. }
  76. })