Quick Start with Mini Program Cloud Development (2/4)

Preface

Let's review the knowledge of "Quick Start with WeChat Mini Program Cloud Development (1/4)" . In the previous chapter, we learned about the advantages and capabilities of cloud development, and we also completed the transformation of the local version of Mazai Memo to the online version. We mainly learned about the cloud database and also directly operated the cloud database by using the cloud API in the mini program:

  • Use get() to query the database
  • Data was added using add()
  • Data modifications were made using update()
  • Data was deleted using remove()

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

List sorting

By default, the list queried by the mini program 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 front, so at this time we need to use the sorting function orderBy to change its sorting rules.

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

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

The parameters are:

  1. Field name to be sorted
  2. Sorting specific rules
  • asc: ascending order, from small to large
  • desc: descending order, from large to small

It supports multiple field combination sorting at the same time, and the priority is determined according to the calling order
. When we learn this API, let’s think about how to implement the specific requirements. There are two ways to achieve this requirement:

Added 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 obtain timestamps

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

Sorting code:

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

Combined time field sorting

In addition, some students have also achieved the same effect without adding new fields, using a combination of multiple fields for sorting.

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

The dates are sorted first, then the times. It should be noted here that some students only sort by time. In this case, if the data on the same day is sorted normally, but in the case of multiple days, the order will be messed up.

Query based on content

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

Use 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 at the same time, it does not occupy the package size of the mini program.
2. Configure the search component in json on the page 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 header
<view>
  <!-- 头部布局 -->
   <view class="page__bd">
    <mp-searchbar bindinput="searchTitle" ></mp-searchbar>
  </view>
  <!-- 列表布局 -->
</view>

display effect:

image.png
4. Monitor input box data

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

At this point, I believe everyone must have felt that it was too late to meet the UI component library. Writing styles is really painful! But having said that, the component library only covers our commonly used components. If the component library does not have components, we still have to write them ourselves. Therefore, the ability to write styles is still very important. You must practice more during the learning process.

Precise query

When we get the data, we start querying it. 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 it when listening

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

Realization effect:

image.png
But in actual scenarios, we often use fuzzy matching, because the title of the memo may be too long, making it difficult for users to remember.

fuzzy query

Here the main purpose is to use regular matching for query conditions and use the RegExp constructor to construct a regular object.

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

Realization effect:

image.png

Paging query

When the memo is used for 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 need for paging will follow. The applet operates the get() function of the cloud database to obtain the data API, and can pull up to 20 items at a time.

So how to do data paging? 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 start from
limit: how many pieces of data to fetch at one time

Let’s implement it based on actual business

  1. Define number of pages and quantity 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. Pass in parameters for the first call
onShow() {
    getMemoList(this.data.pageNo,this.data.pageSize).then(res => {
      this.udpateList(res.data)
    })
  }
  1. Listen for page pull-up callback events
// 上拉加载
  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:

  • Async/await is used in the above logic 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()
}

Specify return

In actual business, list items usually have many details, but the list only needs to display part of the key information. Then at this time, we only need to check the fields that need to be displayed in the list and specify the return results. 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

image.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 parameters 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

Today’s learning:

  1. Database orderBy sorting conditions
  2. Use the extension library WeUI component library
  3. Database where query conditions
  4. Database skip, limit, count combination to achieve paging query
  5. Database field specifies the return field

To learn more about how to get started quickly with small program cloud development, please pay attention to CRMEB

Guess you like

Origin blog.csdn.net/CRMEB/article/details/132078625
Recommended