interface Instance { data$?: Promise } export default PageLoadBehavior(); export function PageLoadBehavior>(method?: () => Promise) { return Behavior({ data: { loading: false, model: null as T | null, }, lifetimes: { created() { if (method) { const context = this as Instance; context.data$ = method(); } }, attached() { const context = this as Instance; 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 }); } } }) }