button.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // components/button/button.ts
  2. Component({
  3. behaviors: ["wx://form-field-button"],
  4. observers: {
  5. loading(this: any, val: boolean) {
  6. // 当外部声明 loading 时,同步禁用状态
  7. this.setData({ isDisabled: !!val });
  8. }
  9. },
  10. lifetimes: {
  11. attached(this: any) {
  12. console.log("[Button] attached, initializing...");
  13. const mode = this.data.block ? "block" : "line";
  14. const index = this.data.index;
  15. this.setData({
  16. src: `../../assets/bg/button-${mode}-${index}.bg.png`,
  17. className: this.data.block ? "block" : `line-${index}`,
  18. isDisabled: false,
  19. });
  20. console.log(
  21. "[Button] initialized with isDisabled:",
  22. this.data.isDisabled
  23. );
  24. },
  25. },
  26. properties: {
  27. block: { type: Boolean, value: false },
  28. index: { type: Number, value: 1 },
  29. loading: { type: Boolean, value: false },
  30. text: { type: String, value: "" },
  31. // 是否在点击后禁用按钮,避免重复提交
  32. disableOnClick: { type: Boolean, value: true },
  33. },
  34. data: {
  35. list: [
  36. {
  37. name: "保存",
  38. value: "save",
  39. },
  40. {
  41. name: "提交",
  42. value: "submit",
  43. },
  44. {
  45. name: "确定",
  46. value: "confirm",
  47. },
  48. {
  49. name: "取消",
  50. value: "cancel",
  51. },
  52. ],
  53. src: "",
  54. isDisabled: false,
  55. _lastResetTime: 0,
  56. },
  57. methods: {
  58. handleSubmit(this: any) {
  59. if (this.data.isDisabled) {
  60. return;
  61. }
  62. // 如果是刚刚重置的按钮(100ms内),不要立即禁用
  63. const now = Date.now();
  64. if (now - this.data._lastResetTime < 100) {
  65. this.triggerEvent("submit");
  66. return;
  67. }
  68. // 点击后可选地禁用按钮,防止重复提交;外部完成后请调用 resetState 或将 loading 置为 false
  69. if (this.data.disableOnClick) {
  70. this.setData({ isDisabled: true });
  71. }
  72. this.triggerEvent("submit");
  73. },
  74. resetState(this: any) {
  75. this.setData({
  76. isDisabled: false,
  77. _lastResetTime: Date.now(),
  78. });
  79. },
  80. valFailure(this: any) {
  81. // 处理失败逻辑
  82. if (this) this.setData({ isDisabled: true }); // 重置按钮状态
  83. },
  84. },
  85. });