| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- interface Instance<T> {
- data$?: Promise<T>
- }
- export default PageLoadBehavior();
- export function PageLoadBehavior<T extends Record<string, any>>(method?: () => Promise<T>) {
- return Behavior({
- data: {
- loading: false,
- model: null as T | null,
- },
- lifetimes: {
- created() {
- if (method) {
- const context = this as Instance<T>;
- context.data$ = method();
- }
- },
- attached() {
- const context = this as Instance<T>;
- if (context.data$ && typeof context.data$.then === 'function') {
- let timer = setTimeout(() => this.showLoading(), 300);
- context.data$
- .then(model => { this.setData({ model }); })
- .finally(() => {
- clearTimeout(timer);
- if (this.data.loading) this.hideLoading();
- })
- }
- }
- },
- methods: {
- showLoading(title = '加载中', mask?: boolean) {
- wx.showLoading({ title, mask });
- this.setData({ loading: true });
- },
- hideLoading() {
- wx.hideLoading();
- this.setData({ loading: false });
- }
- }
- })
- }
|