#小程序云开发挑战赛#-人体生理指标-辰宝宝
发布于 4 年前 作者 mingkong 662 次浏览 来自 分享

应用场景:人体生理指标这个小程序主要是记录自己的血压脉搏数据,方便自己查看了解自己的血压数值数据。

目标用户:高血压血压异常的用户和有需要记录血压脉搏的用户。

实现思路:主要功能就是添加,查询,列表展示。

1.添加:添加功能采用动态列表实现,最多5条最少1条。时间默认使用当前时间,也可以自定义时间。然后通过云开发数据库存储数据。

2.查询:通过日期选择器指定年月日,使用云开发数据库查询数据,再调整指定日期的详情界面。

3.列表展示:分为默认全部展示列表,按月份展示,按天数展示。全部展示列表以时间展示,天数以天数展示,按月份以月份展示。点击月份使用云开发云函数获取指定月份下有记录的天数列表。

架构图:无。

效果截图:

1.首页面有个tab栏,默认展示全部列表,其他还有月份,天数列表。上面还有查询,添加按钮

2.添加界面

3.查询界面

4.详情界面

代码展示:

1.添加界面的代码:

  data: {
    recordTime: "",   //时间
    recordCount: 1,    //记录的总数
    selectDate: "",    //选择的日期
    selectTime: "",    //选择的时间
    isShowPicker: true,  //是否显示日期时间选择控件
    hpInputVal: [],     //高压input的内容
    lpInputVal: [],     //低压input的内容
    pulseInputVal: [],   //脉搏input的内容
  },
  /**高压input */
    hpGetInput: function (e) {
      var curInx = e.currentTarget.dataset.idx;//获取当前索引
      var val = e.detail.value;//获取输入的值
      this.data.hpInputVal[curInx] = val;
    },
    /**低压input */
    lpGetInput: function (e) {
      var curInx = e.currentTarget.dataset.idx;//获取当前索引
      var val = e.detail.value;//获取输入的值
      this.data.lpInputVal[curInx] = val;
    },
    /**脉搏input */
    pulseGetInput: function (e) {
    var curInx = e.currentTarget.dataset.idx;//获取当前索引
    var val = e.detail.value;//获取输入的值
    this.data.pulseInputVal[curInx] = val;
  },
  /**保存记录 */
  saveRecord: function (e) {
    //创建数组
    var recordList = new Array();
    var i;
    for (i = 0; i < this.data.recordCount; i++) {
      //高压
      var hp = this.data.hpInputVal[i];
      //低压
      var lp = this.data.lpInputVal[i];
      //脉搏
      var pulse = this.data.pulseInputVal[i];
      console.log(hp + "," + lp + "," + pulse);
      //创建对象
      var record = new Object();
      record.hp = hp;
      record.lp = lp;
      record.pulse = pulse;
      //加入对象
      recordList[i] = record;
    }
    /**
     * 因为ios不支持new Date(time)的这个time格式为yyyy-mm-dd
     * ios只支持new Date(time)的这个time格式为yyyy/mm/dd
     * 所以这里全部将time的格式转换为yyyy/mm/dd格式
     * 采用str.replace(/-/g, '/')方式将str中'-'符号全部修改为'/'
     */
    var date = new Date(this.data.recordTime.replace(/-/g, '/'))
    var month = date.getFullYear() + '-' + formatNumber(date.getMonth() + 1)
    var day = month + '-' + formatNumber(date.getDate())
    //数据库添加记录
    db.collection(app.globalData.recordTableName).add({
      data: {
        month: month,
        day: day,
        time: util.formatTime(date),
        date: date,
        list: recordList,
      },
      success: function (res) {
        // res 是一个对象,其中有 _id 字段标记刚创建的记录的 id
        console.log(res),
          wx.showToast({
            title: '保存成功',
            duration: 500,
            complete: function (e) {
              //延时器
              setTimeout(function () {
                wx.navigateBack({})
              }, 500) //延迟时间 这里是1秒
            }
          })
      }
    })
  },
 /**wxml添加列表 */
class='record-area' wx:for='{{recordCount}}' wx:key='index'>
  {{index+1}}
  高压
  "number" placeholder="高压" data-idx='{{index}}' bindblur='hpGetInput' />
  低压
  "number" placeholder="低压" data-idx='{{index}}' bindblur='lpGetInput' />
  脉搏
  "number" placeholder="脉搏" data-idx='{{index}}' bindblur='pulseGetInput' />

2.详情界面代码:

  onLoad: function (options) {
    var that = this;
    console.log(options.id)
    //根据id查询记录
    db.collection(app.globalData.recordTableName).doc(options.id).get({
      success: function(res) {
        console.log(res.data)
        that.setData({
          recordObject:res.data
        })
      }
    })
  },
   //详情界面动态列表
'record-area' wx:for='{{recordObject.list}}' wx:key='index'>
  {{index+1}}
  高压
  <input type="number"  value="{{item.hp}}" data-idx='{{index}}' bindblur='hpGetInput' />
  低压
  <input type="number" value="{{item.lp}}" data-idx='{{index}}' bindblur='lpGetInput' />
  脉搏
  <input type="number" value="{{item.pulse}}" data-idx='{{index}}' bindblur='pulseGetInput' />

3.首页

data: {
    navbar: ['全部', '按月份', '按天数'],
    currentTab: 0,
    recordList: [],
    monthList: [],
    dayList: [],
  },
  /** 监听云开发数据库变化*/
  watchRecord() {
    wx.showLoading({
      title: '正在加载...',
    })
    var that = this;
    //监听云开发数据库变化
    db.collection(app.globalData.recordTableName)
      // 按 date 降序
      .orderBy('date', 'desc')
      .where({
        _openid: app.globalData.userOpenID
      })
      .watch({
        onChange: function (snapshot) {
          //是否是初始化
          console.log('is init data', snapshot.type === 'init')
          //改变的事件
          console.log('docs\'s changed events', snapshot.docChanges)
          //改变后的数据
          console.log('query result snapshot after the event', snapshot.docs)
          //首次加载无任何数据,隐藏加载框
          if (snapshot.docChanges.length == 0) {
            wx.hideLoading()
            return
          }
          var record = snapshot.docChanges[0]
          if (record.dataType == "add") {
            //因为添加记录需要将记录添加到最前面,所以这里特殊处理
            that.data.recordList.unshift(record.doc)
            that.setData({
              recordList: that.data.recordList,
            })
          } else {
            //其余的事件在这里统一处理
            that.data.recordList = snapshot.docs
            that.setData({
              recordList: that.data.recordList,
            })
          }
          //根据获取的数据得到月份集合和天数集合
          var monthList = new Array()
          var dayList = new Array()
          for (let i = 0; i < that.data.recordList.length; i++) {
            var record = that.data.recordList[i];
            if (monthList.indexOf(record.month) == -1) {
              monthList.push(record.month)
            }
            if (dayList.indexOf(record.day) == -1) {
              dayList.push(record.day)
            }
          }
          console.log(monthList)
          console.log(dayList)
          //刷新月份和天数的数据
          that.setData({
            monthList: monthList,
            dayList: dayList
          })
          wx.hideLoading()
        },
        onError: function (err) {
          console.error('the watch closed because of error', err)
          wx.hideLoading()
        }
      })
  },
  onLoad: function (e) {
    var that = this;
    //如果用户openid为空,则循环等待app.js获取openid成功
    if (app.globalData.userOpenID == '') {
      var a = setInterval(function () {
        if (app.globalData.userOpenID != '') {
          clearInterval(a)
          that.watchRecord()
        }
      }, 1000)
    } else {
      that.watchRecord()
    }
  },
  /**导航栏 */
  navbarTap: function (e) {
    this.setData({
      currentTab: e.currentTarget.dataset.idx
    })
  },
  /**添加 */
  btAdd: function (e) {
    wx.navigateTo({
      url: '/pages/add/add',
    })
  },
  /**查询 */
  btQuery: function (e) {
    wx.navigateTo({
      url: '/pages/query/query',
    })
  },
  /**进入详情界面 */
  gotoDetail: function (e) {
    let id = e.currentTarget.dataset.id
    setTimeout(() => {
      wx.navigateTo({
        //将数据库id传递过去
        url: '/pages/detail/detail?id=' + id,
      })
    }, 200);
  },
  /**删除 */
  deleteItem: function (e) {
    let id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确定删除记录?',
      success: function (res) {
        if (res.confirm) {  //点击确定
          //根据id删除数据
          db.collection(app.globalData.recordTableName).doc(id).remove({
            success: function (res) {
              console.log(res)
              wx.showToast({
                title: '删除成功',
              })
            },
          })
        }
      },
    })
  },
  /**进入月份 */
  gotoMonthDetail: function (e) {
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      //将数据库id传递过去
      url: '/pages/month/month?id=' + e.currentTarget.dataset.id,
    })
  },
  /**进入天数 */
  gotoDayDetail: function (e) {
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      //将数据库id传递过去
      url: '/pages/day/day?id=' + e.currentTarget.dataset.id,
    })
  },
  /**wxml */
class="row_view">
    <button bindtap="btQuery" class="btn" type="default" style="margin:10rpx;color: #1296db;">查询button>

<button bindtap=“btAdd” class=“btn” type=“default” style=“margin:10rpx;color: #1296db;”>添加button> view> <view class=“navbar”> <text wx:for="{{navbar}}" data-idx="{{index}}“ class=“item {{currentTab==index ? ‘active’ : ‘’}}” wx:key=“unique” bindtap=“navbarTap”>{{item}}text> view> <view hidden=”{{currentTab!==0}}" class=“item_view” wx:for=’{{recordList}}’ wx:key=‘index’> <text data-id="{{item._id}}" bindtap=“gotoDetail" bindlongpress=“deleteItem” >{{item.time}}text> view> <view hidden=”{{currentTab!==1}}" class=“item_view” wx:for=’{{monthList}}’ wx:key=‘index’> <text data-id="{{item}}" bindtap=“gotoMonthDetail” >{{item}}text> view> <view hidden="{{currentTab!==2}}" class=“item_view” wx:for=’{{dayList}}’ wx:key=‘index’> <text data-id="{{item}}" bindtap=“gotoDayDetail” >{{item}}text> view>

4.月份列表界面

/**
     * 调用云函数获取指定月份的所有记录
     * (云函数最多一次可以获取100条数据,小程序一次最多只能获取20条数据,
     * 通过这个云函数可以获取全部的指定数据)
     */
    wx.cloud.callFunction({
      // 云函数名称
      name: 'getRecordsByMonth',
      // 传给云函数的参数
      data: {
        month: id,
        _openid: app.globalData.userOpenID
      },
      success: function (res) {
        console.log(res.result)
        //根据该月份下所有记录得到该月份有哪几天有数据
        var resultList = res.result.data
        var dayList = new Array()
        for (let i = 0; i < resultList.length; i++) {
          var record = resultList[i];
          if (dayList.indexOf(record.day) == -1) {
            dayList.push(record.day)
          }
        }
        that.setData({
          dayList: dayList
        });
        //云函数调用结束,隐藏loading
        wx.hideLoading()
      },
      fail: console.error
    })

/**
 云函数代码
     */
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const MAX_LIMIT = 100
// 云函数入口函数
/**
 * 取指定月份的所有记录
 * [@param](/user/param) {*} event 
 * [@param](/user/param) {*} context 
 */
exports.main = async (event, context) => {
  // 先取出集合记录总数
  const countResult = await db.collection('record').count()
  const total = countResult.total
  // 计算需分几次取
  const batchTimes = Math.ceil(total / MAX_LIMIT)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('record')
      .where({
        month: event.month,
        _openid: event._openid
      })
      .skip(i * MAX_LIMIT)
      .limit(MAX_LIMIT)
      .get()
    tasks.push(promise)
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}

作品二维码:

团队介绍:(队名:辰宝宝)

队长:董湘宁,android开发8年,小程序1年经验

队员:杨柳,小程序开发1个月

回到顶部