Home > Web Front-end > uni-app > body text

Let's talk about uniapp's scroll-view drop-down loading

青灯夜游
Release: 2022-07-14 21:07:08
forward
3642 people have browsed it

Let's talk about uniapp's scroll-view drop-down loading

Recently I am working on a live broadcast module of a WeChat applet. The chat room function in the module is using scroll -view is displayed in the form of a one-dimensional array, and no optimization has been carried out, resulting in a poor user experience

First simulate the chat room## before optimization # SITUATION

Lets talk about uniapps scroll-view drop-down loading

Visible egg pain~

But optimization still has to be optimized. It is impossible not to optimize, but before starting, I think Is it necessary to split the optimization steps into the following two points?

1. No longer use scroll-into-view to set the anchor point

Since the old version is implemented in the form of

scroll-view one-dimensional array, this causes the page to always display the last piece of information after loading after data is added, and It is not the last piece of information before loading, so the previous developer used the scroll-into-view attribute as the return anchor point after the data is loaded, but Since the anchor point pointing to switching and data loading do not occur simultaneously, this leads to the phenomenon of rebound

2. Processing of large amounts of data

Because it is a

chat room function, it is inevitable to load a large amount of user conversations, pictures and other content, and because scroll-view itself is not suitable for loading a large amount of data (it is too bad to think of other methods), so it is necessary to work hard on the loading and display of data

3. Additional function processing

The chat room originally had

return to the bottom and other functions, so the original functions cannot be ignored after the optimization is completed

OK to start~

1. Invert scroll-view

Why should we invert

scroll-view? From the first point above, we can see that if data needs to be inserted in positive order, there will inevitably be a situation where the subsequent data cannot be displayed after the data is loaded , but if you want to solve this situation, You need to use the scroll-into-view attribute, then if you need to completely solve this problem, you need to start with the root of the problem scroll-view

First of all

The code of before modification?

<view>这是一个直播画面</view>
  <scroll-view>
    <view>
      {{ item.data }}
    </view>
  </scroll-view>
Copy after login
const scrollIntoView = ref("index1");
const upper = () => {
  let lastNum = scrollData.value[0].data;
  let newArr = [];
  for (let index = 1; index  {
    scrollIntoView.value = `index${lastNum}`;
    console.log("scrollIntoView  :>>", scrollIntoView.value);
  }, 100);
};
const getRandomColor = () => {
  return "#" + Math.random().toString(16).substr(2, 6);
};
Copy after login
Then let’s try it first

Invert scroll-viewIt has no effect in the end

First we need to give

scroll -viewApply a transform:rotate(180deg) attribute, and then apply the same attribute to the internal child elements. Don’t forget to array to store the dataAlso invert it. The most important thing is to remove the scroll-into-view attribute on scroll-view. Will you get this effect?

Lets talk about uniapps scroll-view drop-down loading

Also, the position of the

scroll bar is on the left at this time. If necessary, you can use the CSS attribute to remove it, or simulate it yourself. The following is to Removing the CSS style of the scroll bar?

::-webkit-scrollbar {
  display:none;
  width:0;
  height:0;
  color:transparent;
}
Copy after login
This is just the

first step, the next step is how to pull down and load data.

At this time our

scroll-view is in an inverted state, that is to say the top is the bottom and the bottom is the top(Put it aside Tongue twister), so the scrolltoupper top method used before must be replaced with scrolltolower bottom method to achieve "pull-down loading"

Lets talk about uniapps scroll-view drop-down loading

Below is the current

Chat roomLooks much better

Lets talk about uniapps scroll-view drop-down loading

2、大量数据的处理

处理完回弹问题后,就需要考虑如何处理大量数据。由于uni-app官方也在文档中提到scroll-view加载大批量数据的时候性能较差,但无奈手头上也没有别的办法,只能死马当活马医了

我第一个想法就是非常经典的虚拟列表,但是此前所看的很多关于虚拟列表的文章都是在web端实现的,似乎小程序领域里并不是一个被经常采用的方法,但是所幸还是找到了如何在微信小程序实现虚拟列表的资料,详情可以查看这篇文章?微信小程序虚拟列表

OK说干就干,那么第一步就是要明确实现虚拟列表需要什么样的数据结构,虚拟列表其实简单地说就是当某一个模块的数据超出了可视范围就将其隐藏,那么如何将数据分为多个模块呢?答案就是二维数组

首先将当前的页码存储起来(默认为0),当触发下拉加载动作时页码+1,然后以当前页码作为下标存入数组

const currentShowPage=ref(0)
const upper = () => {
  let len = scrollData.value[currentShowPage.value].length - 1;
  let lastNum = scrollData.value[currentShowPage.value][len].data;
  let newArr = [];
  currentShowPage.value += 1;
  for (let index = 1; index <p>当然别忘了在页面中也需要以<code>二维数组</code>的形式循环数据</p><pre class="brush:php;toolbar:false"><scroll-view>
    <view>
      <view>
        {{ item.data }}
      </view>
    </view>
  </scroll-view>
Copy after login
数据结构的问题解决了,那么接下来就是如何判断数据模块是否超出可视范围

首先我们需要知道每个数据模块的高度,其实很简单,只需要为每个模块定义一个id,然后在数据展示之后根据id获取到该模块的节点信息然后按顺序存储到数组中即可

const pagesHeight = []
onReady(()=>{
    setPageHeight()
})

const upper = () => {
  ...
  nextTick(() => {
    // 每次获取新数据都调用一下
    setPageHeight();
  });
};

const setPageHeight = () => {
  let query = uni.createSelectorQuery();
  query
    .select(`#item-${currentShowPage.value}`)
    .boundingClientRect(res => {
      pagesHeight[currentShowPage.value] = res && res.height;
    })
    .exec();
};
Copy after login

OK,现在我们已经知道每个模块的高度了,然后就是监听模块与可视窗口的交叉范围。这里有两种方法,一种是JS获取可视窗口的高度与模块scrollTop进行差值计算,另一种是使用小程序的createIntersectionObserver方法让程序自行监听交叉区域

这里我展示的是第二种方法,如果对第一种方法感兴趣的朋友可以向上看第二章开头我推荐的《微信小程序虚拟列表》文章

关于createIntersectionObserver方法的使用其实很简单,我们只需要把可视窗口的id以及需要监听的模块id传入即可,详情看官方文档

onReady(() => {
  ...
  observer(currentShowPage.value);
});
const upper = () => {
  ...
  nextTick(() => {
    // 每次获取新数据都调用一下
    observer();
  });
};

// 允许渲染的数组下标,需要设置默认值
const visiblePagesList = ref([-1,0,1])
const observer = pageNum => {
  const observeView = wx
    .createIntersectionObserver()
    .relativeTo("#scroll", { top: 0, bottom: 0 });
  observeView.observe(`#item-${pageNum}`, res => {
    if (res.intersectionRatio > 0) visiblePagesList.value = [pageNum - 1, pageNum, pageNum + 1];
  });
};
Copy after login

最后就是在页面中判断该模块是否允许被渲染(也就是是否存储在visiblePagesList数组中),这里就很简单了,只需要写一个方法在页面中调用即可

<scroll-view>
    <view>
      <template>
        <view>
          {{ item.data }}
        </view>
      </template>
      <view></view>
    </view>
  </scroll-view>
Copy after login
const includePage = index => {
  return visiblePagesList.value.indexOf(index) > -1;
};
Copy after login

来看看效果如何

Lets talk about uniapps scroll-view drop-down loading

额...似乎没有太大区别,那我们看看页面结构到底也没有将可视区域外的内容切换为空白view

Lets talk about uniapps scroll-view drop-down loading

成功!

3、功能调整

聊天室原本还有回底功能等,也不能忘了加上

这个部分就比较简单了,只需要直接使用scroll-viewscroll-top属性,然后通过在scroll回调中动态记载scroll-top的值即可

下面是部分代码

<scroll-view>
  ...
  </scroll-view>
  <view>回底</view>
Copy after login
let scrollTop;
const currentTop = ref(0);
const showGoBottom = ref(false);
const handle_scroll = throttle(event => {
  scrollTop = event[0].detail.scrollTop;
  if (scrollTop > 300) {
    showGoBottom.value = true;
  }
}, 100);
const handle_goBottom = () => {
  currentTop.value = scrollTop;
  nextTick(() => {
    currentTop.value = 0;
  });
  showGoBottom.value = false;
};
Copy after login

大功告成~

最后附上demo仓库

https://gitee.com/huang-qihao123/virtual-list-demo

推荐:《uniapp教程

The above is the detailed content of Let's talk about uniapp's scroll-view drop-down loading. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!