index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { getAllRect } from '../common/utils';
  2. import { VantComponent } from '../common/component';
  3. import { canIUseModel } from '../common/version';
  4. VantComponent({
  5. field: true,
  6. classes: ['icon-class'],
  7. props: {
  8. value: {
  9. type: Number,
  10. observer(value) {
  11. if (value !== this.data.innerValue) {
  12. this.setData({ innerValue: value });
  13. }
  14. },
  15. },
  16. readonly: Boolean,
  17. disabled: Boolean,
  18. allowHalf: Boolean,
  19. size: null,
  20. icon: {
  21. type: String,
  22. value: 'star',
  23. },
  24. voidIcon: {
  25. type: String,
  26. value: 'star-o',
  27. },
  28. color: String,
  29. voidColor: String,
  30. disabledColor: String,
  31. count: {
  32. type: Number,
  33. value: 5,
  34. observer(value) {
  35. this.setData({ innerCountArray: Array.from({ length: value }) });
  36. },
  37. },
  38. gutter: null,
  39. touchable: {
  40. type: Boolean,
  41. value: true,
  42. },
  43. },
  44. data: {
  45. innerValue: 0,
  46. innerCountArray: Array.from({ length: 5 }),
  47. },
  48. methods: {
  49. onSelect(event) {
  50. const { data } = this;
  51. const { score } = event.currentTarget.dataset;
  52. if (!data.disabled && !data.readonly) {
  53. this.setData({ innerValue: score + 1 });
  54. if (canIUseModel()) {
  55. this.setData({ value: score + 1 });
  56. }
  57. wx.nextTick(() => {
  58. this.$emit('input', score + 1);
  59. this.$emit('change', score + 1);
  60. });
  61. }
  62. },
  63. onTouchMove(event) {
  64. const { touchable } = this.data;
  65. if (!touchable)
  66. return;
  67. const { clientX } = event.touches[0];
  68. getAllRect(this, '.van-rate__icon').then((list) => {
  69. const target = list
  70. .sort((cur, next) => cur.dataset.score - next.dataset.score)
  71. .find((item) => clientX >= item.left && clientX <= item.right);
  72. if (target != null) {
  73. this.onSelect(Object.assign(Object.assign({}, event), { currentTarget: target }));
  74. }
  75. });
  76. },
  77. },
  78. });