page-loading.behavior.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. interface Instance<T> {
  2. data$?: Promise<T>
  3. }
  4. export default PageLoadBehavior();
  5. export function PageLoadBehavior<T extends Record<string, any>>(method?: () => Promise<T>) {
  6. return Behavior({
  7. data: {
  8. loading: false,
  9. model: null as T | null,
  10. },
  11. lifetimes: {
  12. created() {
  13. if (method) {
  14. const context = this as Instance<T>;
  15. context.data$ = method();
  16. }
  17. },
  18. attached() {
  19. const context = this as Instance<T>;
  20. if (context.data$ && typeof context.data$.then === 'function') {
  21. let timer = setTimeout(() => this.showLoading(), 300);
  22. context.data$
  23. .then(model => { this.setData({ model }); })
  24. .finally(() => {
  25. clearTimeout(timer);
  26. if (this.data.loading) this.hideLoading();
  27. })
  28. }
  29. }
  30. },
  31. methods: {
  32. showLoading(title = '加载中', mask?: boolean) {
  33. wx.showLoading({ title, mask });
  34. this.setData({ loading: true });
  35. },
  36. hideLoading() {
  37. wx.hideLoading();
  38. this.setData({ loading: false });
  39. }
  40. }
  41. })
  42. }