A few days ago, I shared an open source project on applets component extension (Portal).

I was trying to cheat STAR on my first open source code release, but I was a little embarrassed when a lot of nice friends gave the article a thumbs up, so I decided to write a little dry stuff about how to do it.

First, set the height of the scrollview under the component to 40px higher than the component itself, that is, the height of the area where the updated text is displayed in the head, and then set the Y-axis of the scrollview to -40px so that the updated text area is not visible at the top. The specific CSS is as follows:

.scroll-view {
  height: calc(100% + 40px);
  transform: translateY(-40px);
}
Copy the code

Then it is to listen to the onscroll event of the scroll view. Here I divide the state of the drop-down refresh into five types:

// This is not written in the code, directly use the number
const _pullDownStatusDic =  {
  invisiable: 0./ / see nothing
  pulling: 1./ / the drop-down
  release: 2.// Can be released when refreshing
  refresing: 3.// Refresh
  finish: 4.// Refresh complete
}
Copy the code

So in the event listener, according to the current scrollTop to determine which state should be:

// Height is the default drop height to refresh
if (scrollTop < - 1 * height) {
  targetStatus = 2;
} else if (scrollTop < 0) {
  targetStatus = 1;
} else {
  targetStatus = 0;
}
Copy the code

The question is, when do you refresh? There is no event like onscrollend in the scroll view of the mini program, so I thought of onTouchEnd. After all, on the phone, you can only slide by touch (except by clicking the head to return to the top). So only need in the event of an ontouchend to monitor if the current state of the drop-down is 2 (_pullDownStatusDic. Release) loosen can be refreshed and will trigger a refresh:

if (status === 2) {
  this.setData({
    pullDownStatus: 3,})this.properties.refreshing = true.this.triggerEvent('pulldownrefresh');
}
Copy the code

Of course, there is a problem at this time, we need to display the refresh text locally, we cannot set the scrollTop of an Scroll view to negative, so we have to cancel the Y-axis offset of the Scroll view to solve the problem. I will try to optimize it in the later stage.

After the refresh, animate the Y-axis offset of the Scroll View through the CSS and change it back to -40px (translate instead of margin), thus completing a pull-down refresh.

Isn’t it easy 🙂

There are also some small details, there are more loading, and some implementation of Xing-image, it is more simple, interested can look at the source code

Star: View on Github