button.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. },
  56. methods: {
  57. onSubmit(this: any, event: any) {
  58. if (this.data.isDisabled) return;
  59. if (this.data.disableOnClick) this.valFailure();
  60. this.triggerEvent('submit', { target: event.target }, { bubbles: true, composed: true });
  61. },
  62. resetState(this: any) {
  63. this.setData({
  64. isDisabled: false,
  65. });
  66. },
  67. valFailure(this: any) {
  68. // 处理失败逻辑
  69. if (this) this.setData({ isDisabled: true }); // 重置按钮状态
  70. },
  71. },
  72. });