button.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // components/button/button.ts
  2. Component({
  3. behaviors: ["wx://form-field-button"],
  4. observers: {
  5. loading(this: any, val: boolean) {
  6. // 当外部声明 loading 时,同步禁用状态
  7. if (this.data.disableOnClick) this.setData({ isDisabled: !!val });
  8. },
  9. },
  10. lifetimes: {
  11. attached(this: any) {
  12. const mode = this.data.block ? "block" : "line";
  13. const index = this.data.index;
  14. this.setData({
  15. src: `../../assets/bg/button-${mode}-${index}.bg.png`,
  16. className: this.data.block ? "block" : `line-${index}`,
  17. isDisabled: false,
  18. });
  19. },
  20. },
  21. properties: {
  22. block: { type: Boolean, value: false },
  23. index: { type: Number, value: 1 },
  24. loading: { type: Boolean, value: false },
  25. text: { type: String, value: "" },
  26. // 是否在点击后禁用按钮,避免重复提交
  27. disableOnClick: { type: Boolean, value: true },
  28. },
  29. data: {
  30. list: [
  31. {
  32. name: "保存",
  33. value: "save",
  34. },
  35. {
  36. name: "提交",
  37. value: "submit",
  38. },
  39. {
  40. name: "确定",
  41. value: "confirm",
  42. },
  43. {
  44. name: "取消",
  45. value: "cancel",
  46. },
  47. ],
  48. src: "",
  49. isDisabled: false,
  50. },
  51. methods: {
  52. onSubmit(this: any, event: any) {
  53. if (this.data.isDisabled) return;
  54. if (this.data.disableOnClick) this.valFailure();
  55. this.triggerEvent('submit', { target: event.target }, { bubbles: true, composed: true });
  56. },
  57. resetState(this: any) {
  58. this.setData({
  59. isDisabled: false,
  60. });
  61. },
  62. valFailure(this: any) {
  63. // 处理失败逻辑
  64. if (this) this.setData({ isDisabled: true }); // 重置按钮状态
  65. },
  66. },
  67. });