Quick Start for WeChat Mini Program Cloud Development (2/4)

foreword

Let's review the knowledge of "WeChat Mini Program Cloud Development Quick Start (1/4)" . In the previous chapter, we learned about the advantages and capabilities of cloud development, and we also completed the transformation from the local version of the code boy memo to the online version. We mainly learned about cloud databases and directly operated cloud databases by using cloud APIs in applets:

  • Use get() to query the database
  • Added data using add()
  • Data modification using update()
  • Data was deleted using remove()

This chapter brings you the four query methods of "sorting", "precise", "fuzzy" and "paging", which are also often used in actual business.

list sort

By default, the list queried by the applet is sorted by time, with the latest added data at the end. But the actual requirement is that the latest addition needs to be at the top, so at this time we need to use the sorting function orderBy to change its sorting rules.

The specific usage method in orderBy (the method directly chained through the database object, used before using the get method):
document sample code: sort ascending order by progress to-do items

db.collection('todos').orderBy('progress', 'asc')
  .get()
  .then(console.log)
  .catch(console.error)

The parameters are:

  1. The name of the field to be sorted
  2. Sort specific rules
  • asc: ascending order, from small to large
  • desc: descending order, from big to small

At the same time, it supports combination and sorting of multiple fields, and the priority is determined according to the calling order
. When we learn this API, let us think about how to realize the specific requirements. There are two ways to realize this requirement:

New time field sorting

At this time, we can set the timestamp field createTime when adding/modifying, and then sort by the timestamp field.
Add the createTime attribute code and write it in the save method of the edit page
4 ways to get the timestamp

let createTime1 = Date.parse(new Date()); // 精确到秒
let createTime2 = new Date().getTime(); // 精确到毫秒
let createTime3 = new Date().valueOf(); // 精确到毫秒
let createTime4 = Date.now(); // 精确到毫秒,实际上是new Date().getTime()

Sort code:

db.collection('memo').orderBy('createTime', 'desc').get()

Combined time field sorting

In addition, some students have achieved the same effect without adding new fields, using multiple fields to sort.

db.collection('memo').orderBy('date','desc').orderBy('time','desc').get()

The date is sorted first, and then the time is sorted. It should be noted here that some students only sort the time. In this case, if the data of the same day is sorted normally, but if it is multiple days, the order will be messed up.

Query by content

In order to find the memo more efficiently, search is essential. Next, we will use the where function to implement the search function. First of all, we need a search box, and here I will tell you a little trick. Some commonly used components can be quickly implemented by referencing the mature UI component library. Last time we learned to use the npm application time toolkit. Next, we will expand The library imports WeUI components.

Use the UI component library

  1. Configure in app.json:
{
  "useExtendedLib": {
    "weui": true
  }
}

It is equivalent to introducing the latest version of the npm package related to the corresponding extension library, and it does not occupy the package size of the applet.
2. Configure the search component in the page json used

{
  "usingComponents": {
    "mp-searchbar": "weui-miniprogram/searchbar/searchbar"
  }
}

  1. Add layout code where needed on the page, insert it above the list and below the head
<view>
  <!-- 头部布局 -->
   <view class="page__bd">
    <mp-searchbar bindinput="searchTitle" ></mp-searchbar>
  </view>
  <!-- 列表布局 -->
</view>

display effect:

6fec9202308041703293100.png

4. Monitor input box data

searchTitle: function (event) {
    console.log('search',event.detail.value)
  }

At this point, I believe that everyone must have a feeling that they have met each other lately for the UI component library. Writing styles is really painful! But having said that, the component library only covers our commonly used components. If there are no components in the component library, we still have to write them honestly. Therefore, the ability to write styles is still very important, and we must practice more during the learning process.

Accurate query

When we get the data, we start to query. Here we need to modify our getMemoList function.

// 获取备忘录列表,支持搜索标题
function getMemoList(value) {
  // 1. 获取数据库引用
  const db = wx.cloud.database()
  // 2. 找到集合获取数据
  let memo = db.collection('memo')
  // 3. 判断是否有查询数据
  if (value) {
    memo = memo.where({
      title: value
    })
  }
  // 4. 判断查询返回数据
  return memo.orderBy('createTime', 'desc').get()
}

Then call when listening

searchTitle: function (event) {
    let value = event.detail.value
    getMemoList(value).then(res=>{
      console.log(res.data)
      this.udpateList(res.data)
    })
  }

Realize the effect:

598bc202308041703525165.png

But in actual scenarios, we often use fuzzy matching, because the title of the memo may be too long, which is not easy for users to remember.

fuzzy query

Here, the query conditions are mainly matched with regular expressions, and the RegExp constructor is used to construct regular object.

memo.where({
      title: db.RegExp({
        regexp: value, //从搜索栏中获取的value作为规则进行匹配。
        options: 'i', //大小写不区分
    })

Realize the effect:

34724202308041704078885.png

Paging query

When the memo is used longer and longer, the data will also increase. At this time, the actual demand does not need to be loaded all at once, so the demand for paging will follow. The applet side operates the get() of the cloud database to obtain data APIs, and can pull up to 20 records at a time.

So how to paginate data? The official case is given:

db.collection('todos')
  .where({
    _openid: 'xxx', // 填入当前用户 openid
  })
  .skip(10) // 跳过结果集中的前 10 条,从第 11 条开始返回
  .limit(10) // 限制返回数量为 10 条
  .get()
  .then(res => {
    console.log(res.data)
  })
  .catch(err => {
    console.error(err)
  })

Mainly through skip and limit.
skip: how many pieces of data to take from the first
limit: how many pieces of data to take at one time

Let's implement it according to the actual business

  1. Define the number of pages and the amount per page
 /**
   * 页面的初始数据
   */
  data: {
    pageNo:0, // 默认第一页
    pageSize:5, // 一页5条数据
  },

  1. Transform list data query function
function getMemoList(pageNo, pageSize) {
  const db = wx.cloud.database()
  return db.collection('memo')
    .skip(pageNo * pageSize)
    .limit(pageSize)
    .orderBy('createTime', 'desc')
    .get()
}

  1. Parameters passed in for the first call
onShow() {
    getMemoList(this.data.pageNo,this.data.pageSize).then(res => {
      this.udpateList(res.data)
    })
  }

  1. Listen to the page pull callback event
// 上拉加载
  onReachBottom (){
    this.loadList()
  }

  1. Implement specific data loading logic
async loadList(){
    // 1. 获取总条数
    let {total} = await getListTotal()
    // 2. 判断是否全部已经加载完毕
    if(this.data.list.length<total){
     // 如果没有加载完
     // 提示数据加载中
      wx.showLoading({
        title: '数据加载中...',
      })
      // 当前页+1
      this.data.pageNo ++
      // 获取下一页数据
      let {data} = await getMemoList(this.data.pageNo,this.data.pageSize)
      this.setData({
        // 拼接数据,页面展示
        list:this.data.list.concat(data)
      })
      // 关闭加载提示
       wx.hideLoading()
    }else{
    // 加载完成提示:“无更多数据”
      wx.showToast({
        icon:'error',
        title: '无更多数据',
      })
    }
  },

Notice:

  • In the above logic, async/await is used to reduce callbacks and make the code more readable and writable.
  • The getListTotal used in the above logic to obtain the total number of lists uses the count function.
function getListTotal() {
  const db = wx.cloud.database()
  return db.collection('memo').count()
}

specified return

In actual business, there are usually many details of list subitems, but the list only needs to display some key information. At this time, we only need to check the fields that need to be displayed in the list, and specify the return result. If there are no necessary fields, there is no need to return. Use field accomplish.
For example: the current list only needs to display the title field data.

// 获取备忘录列表
function getMemoList(pageNo, pageSize) {
  const db = wx.cloud.database()
  return db.collection('memo')
    .field({
      title: true,
    })
    .get()
}

data return

26ad5202308041705045924.png

In actual business scenarios, the list usually does not query all the data. Clicking on the details will query all the data through the id. Therefore, the best way to pass the id field from the list page to the details page is to pass the id field instead of passing the list click object. Go to the details page.

Summarize

Learn today:

  1. Database orderBy sorting condition
  2. Use the extension library WeUI component library
  3. Database where query condition
  4. The combination of database skip, limit, and count realizes paged query
  5. Database field specifies the returned field

Guess you like

Origin blog.csdn.net/weixin_64051447/article/details/132295519