Mini Program Page Monitoring

There are many kinds of applets, such as WeChat applet, Dingding applet, uni-app, Taro
and so on.
Page monitoring has a life cycle in an applet.

When you search the life cycle of the applet, you can find two methods, onShow and onHide, which are
used to monitor whether the page is displayed, and one is used to monitor whether the page is hidden.

But sometimes, we cannot use the life cycle of the applet.
For example, a project in my hand uses the vue + vant method to write a small program page. How to detect whether a certain component is displayed in the vue component?

Via routing? Route guard? As long as you jump to that page, the function in the router guard will be triggered. This is indeed a method, but it always feels a bit troublesome.

Introduce a simple method. Binding events are used to monitor whether the page is redisplayed.

绑定名为resume的事件,第二个参数function就是监视是否显示该页面的回调
document.addEventListener('resume', function(){
    
    });

For Vue, the resume event should be bound to the document in mounted, and this event should be cleared when the component is destroyed.
Digression: If there is a countdown, it should also be cleared in the beforeDestory life cycle.

mounted() {
    
    
  // 加载数据状态
  this.fetchData();
  // 每次返回都需要在再添加
  document.addEventListener('resume', this.fetchData);
},
beforeDestroy() {
    
    
  // 组件销毁前清除自定义事件
  document.removeEventListener('resume', this.fetchData);
},

Guess you like

Origin blog.csdn.net/glorydx/article/details/111386815
Recommended