Vue Ecology – Multi-terminal solution UNI-app

Updated 0926, 2021

This article is updated because of its high ranking in search engines and in order to solve problems for you

This is my Github github address mentioned below may exist invalid

Uni App Ecology drop-down refresh source code

<template> <! -- <view class="content"> <image class="logo" src="/static/logo.png"></image> <view class="text-area"> <text class="title">{{title}}</text> </view> <view class=""> 123 </view> </view> --> <view class="content"> <ItemComp :item="item" v-for="(item,index) in list" :key="index" /> <! - at the bottom of the document - > < the view class = "" > < text > {{status = = = 'more'? contentText.contentdown : (status === 'loading' ? contentText.contentrefresh : contentText.contentnomore)}}</text> </view> </view> </template> <script> import ItemComp from '.. /.. /components/item.vue' export default { data() { return { title: 'Hello', url:`https://reqres.in/api/users`, list:[], page:1, per_page:10, status:'more', // Default display pull-up shows more contentText:{contentDown: "Pull-up shows more ", contentRefresh:" loading..." , contentnomore: }}, components:{ItemComp}, onShow() {this.page =1 this.per_page = 10 this.list = []}, components:{ItemComp}, onShow() {this.page =1 this.per_page = 10 this.list = []}, OnLoad () {this.page = 1 // initialize the list data this.fetchData()}, // Pull downRefresh onPullDownRefresh(val){this.page = 1 this.per_page = 10 console.log(' pull refresh ',val) this.fetchData().then(()=>{this.page = 1 this.per_page = 10 console.log(' pull refresh ',val) this.fetchData().then(()=>{ uni.stopPullDownRefresh(); }).catch(err=>{ uni.stopPullDownRefresh(); Uni. showToast({title: 'request error ', icon: 'none' }) }) }, // Pull-up loading triggers onReachBottom(){// Change the state to loading this.status = 'loading' // page number changes ++this.page // load more FetchData ('loadMore'). Then (resArray=>{if(resarray.length){this.status = 'more'}else{ this.status = 'noMore'; --this.page; }}). The catch (err = > {the console. The log (' network request failed ')})}, the methods: { fetchData(way){ return new Promise((resolve,reject)=>{ uni.request({ url:this.url, data:{ page:this.page, per_page:this.per_page }, success: (res) => {console.log(res) // When page data const resDataArray = res.data.data if(way==='loadMore'){this.list = This.list. Concat (resDataArray)}else{this.list = resDataArray} resolve(resDataArray)}, Fail (err) {console.log(' interface call failed ',err) // Reject ()}})})}} </script> <style> /*. Content {display: flex; flex-direction: column; align-items: center; justify-content: center; } */ .content{ width: 100%; } </style>Copy the code

List page pull up to load more, pull down to refresh effect

Easily pull up load, pull down refresh, back to the top

Implementation effect

preparation

The backend interface

In this small case, we used the open source JsonPlaceholder, which is also our common front-end test interface. For the sake of a small demo, use this for the moment, then replace it with douban-api

  • JSONPlaceholder is available directly in the browser

We don’t even use mock interfaces, and the most important thing is support for paging queries, which take the parameter

  • offset
  • limit

If you are writing in the background, you should be familiar with these two fields. Offset stands for offset, which is also mentioned on the Nest website

{
    "page": 1,"limit"10} :Copy the code

At the time of the request it’s something like this, the information of the page that was passed, but the parameters that we entered

{
    "_offset":xx, // where xx stands for what page"_limit":xx // where xx represents how many pieces of data per page}Copy the code

Below we in your browser’s address bar (or use the postman | postwoman | Vscode plug-in can be) https://jsonplaceholder.typicode.com/posts

The result returned is:

[{"userId": 1."id": 1."title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"."body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1."id": 2."title": "qui est esse"."body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1."id": 3."title": "ea molestias quasi exercitationem repellat qui ipsa sit aut"."body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"}]...Copy the code

So we’re doing more pull-up loading and most importantly, the page number changes every time

_offset++;
Copy the code

Uni-app Network request API

  • Uni-app portal

The official website makes it clear that we can pass in a configuration OBJECT through uni.Request (OBJECT), which is worth mentioning that the default is GET request

uni.request({
  url: "https://jsonplaceholder.typicode.com/posts".// The requested address

  success: res= > {
    console.log(res); }});Copy the code

Item Item

We know that in front-end development it is a common business requirement to generate items from a list loop in the background, followed by pull-up loading and pull-down refreshing. So in this small case, let’s use the card layout. I recommend it to the official Hello-uniapp in maintenance

  • Making transfer, which maintains many common effects. Here we try tocloneThe latest code, as it is still updated very frequently, is mainly to address some on different devicesbug

Do it

  • Asynchronously retrieving data
	// Get list data asynchronously
getDataList() {
    uni.request({
        url: 'https://jsonplaceholder.typicode.com/posts'.// This is an example, not a real interface address.

        success: (res) = > {
                console.log(res)
        }
    });
},
Copy the code

That is to get all the data, which is not in accordance with the specification in actual development

  • The introduction of the plugin

Generally we expect a drop-down refresh and a drop-down load to go back to the top of the list when the data is looping, so we use a third party library, which I think is very useful

Delicate pull-down refresh and pull-up load JS framework. Support VUE, perfect for mobile and mainstream PC browsers star number is currently 2.8K

It can also be used in other development solutions, of course, there is a version of UniApp, before using it, let’s take a look at the structural layout section


	 <mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption" >
		 <view v-for="(item,index) in dataList" :key="`item${index}`">  </view>
	 </mescroll-body>

Copy the code

Among them

Properties or methods meaning
ref=”mescrollRef” Bytedance applet ref=”mescrollRef” must be configured
@init=”mescrollInit” Must be configured
@down=”downCallback” Must be configured
@up=”upCallback” Must be configured
:down=”downOption” Common configurations for drop-down refresh
:up=”upOption” Common configurations for pull-up loading

Since we need to use this effect in many parts of a project, we simply import it globally and register it as a global component

// Register the global component in main.js
import MescrollBody from "@/components/mescroll-uni/mescroll-body.vue";
import MescrollUni from "@/components/mescroll-uni/mescroll-uni.vue";
Vue.component("mescroll-body", MescrollBody);
Vue.component("mescroll-uni", MescrollUni);
Copy the code
  • Pages. Json configuration
{
		"path": "pages/findMovie/findMovie"."style": {
			"navigationBarTitleText": "Looking for"."enablePullDownRefresh": false."app-plus": {
				"bounce": "none" // Delete this item: mescroll-body supports iOS rebound}}},Copy the code

There are two core approaches

methods meaning
upCallback(page) Pull-up loaded callback
downCallback() Pull down the refresh callback

Before we proceed to the next section, we need to know how to calculate the total number of pages of data returned by the interface

Math.ceil(5 / 2);
Math.ceil(26 / 10);
Math.ceil(100 / 10);
Math.ceil(20 / 4);
Copy the code

  • The core code
/* Pull-up loaded callback */
upCallback({num,size}) {
/ / the console. The log (num, size), / / 1
uni.request({
    url: `https://jsonplaceholder.typicode.com/posts`.data: {
        _offset: num,
        _limit: size
    },
    success: (data) = > {
        // The interface returns the current page data list (array)
        let curPageData = data.data;
        // curPageLen=8; // curPageLen=8;
        let curPageLen = data.data.length;
        // The total number of pages returned by the interface (if the list has 26 data, 10 pages per page, a total of 3 pages; The totalPage = 3)
        let totalPage = Math.ceil(100/size); // go up
        // The total amount of data returned by the interface (for example, the list has 26 data, 10 data per page, a total of 3 pages; TotalSize = 26)
        let totalSize = 100;
        // Does the interface return the next page (true/false)
        // let hasNext = data.xxx;

        // Set the list data
        if (this.mescroll.num == 1) this.dataList = []; // Manually empty the list if it is the first page
        this.dataList = this.dataList.concat(curPageData); // Append new data

        // The request succeeded, hiding the loading status
        // method 1 (recommended): the background interface returns the totalPage of the list totalPage
        this.mescroll.endByPage(curPageLen, totalPage);

        // Method 2 (recommended): the background interface returns the total data size of the list
        //this.mescroll.endBySize(curPageLen, totalSize);

        // Method 3 (recommended): You have other ways to know if there is a next hasNext page
        //this.mescroll.endSuccess(curPageLen, hasNext);
    },
    fail: () = > {
        // Request failed to hide load status
        this.mescroll.endErr()
    }
})
},
Copy the code

Write in the last

The project of Uniapp-Douban-movie is a personal training project of Uniapp, a multi-terminal solution based on Vue ecology, which is constantly updated and maintained by the author. Some requirements encountered in actual development will be summarized in this small project with several features

  • Update time is uncertain
  • The code syncs with Github
  • Imitate as much as possibleDouban movie UI

The module

Effect of name other
In the project, the list page pulls up to load more, and pulls down to refresh the effect

If it’s fun, you might want to sync a star code here


Although it is over, thank you