Introduction to WeChat Mini Program Cloud Development Practice

Introduction to Cloud Development

What is cloud development?
After the release of the WeChat applet in 2017, the former development model was to use the relevant components of the WeChat applet on the front-end page. When it comes to background login and business interaction, you need to use a self-built server, whether it is PHP or JAVA architecture needs to expose corresponding interfaces for WeChat applet calls. This development mode has a complex technical architecture and difficult development and debugging, and is suitable for professional companies with relatively mature businesses.
Later, with the development of technology, WeChat introduced a cloud development model. The front-end is still developed using WeChat related components, but the NodeJS back-end built by WeChat only needs to encapsulate the corresponding business logic into functions for the front-end to call. , The database uses MongoDB, which can create collections and database records online, which is very convenient to use. And because the front-end and back-end technologies use WeChat's self-built technology, there is no need to rent a third-party server, and the program can be deployed automatically. After going online and passing the WeChat official code review, you only need to pay according to the used traffic, and it will be the same as the mobile phone card. Similarly, how much traffic will be available for how much monthly rent is activated. In addition, there is a free traffic in the early stage. A monthly rent of 100 yuan per month is enough for general applications, which is very convenient from development to operation and maintenance.

How to
activate cloud development? First, you need to visit the official address of WeChat official account: https://mp.weixin.qq.com/, and register an account by yourself
Website homepage
. Choose the mini program on the main body selection page
Subject selection
because you need to register by email, which will also be in the future Log in to the account, just follow the requirements. When you
Insert picture description here
log in, you need to register with the administrator's WeChat code for authentication. After passing, you can open the background management page of the applet. The
Insert picture description here
daily functions that are frequently used are version management and users. Management, version management is the experience version can be set after the code is submitted, then the experience personnel in user management can use the mobile phone to experience the specific effects of the applet you made. User management is mainly used to increase experience personnel, of course, you can also set up developers. In short, these two functions are quite easy to use.
Insert picture description here
Environment setup
In addition to the daily operations in the background, like JAVA development, there will be development tools. WeChat applet development also has its own development tools. You can download and install the tools under the document column of the background navigation bar. The
Insert picture description here
Insert picture description here
specific installation will not be introduced. Simple, just follow the prompts all the way to the next step. After the
project creation
tool is installed, double-click the icon to open it. I want to emphasize that a knowledge point is the APPID. This is equivalent to the unique identification code of the applet. It is required to fill in the daily project creation. How to find this ID? Open the development section in the background:
Insert picture description here
you can find it.
After the installation is complete, double-click the installed icon
Insert picture description here
. Click the + sign to create a project in the opened interface.
Insert picture description here
Select the directory that the project needs to create, enter the project name, and the most important thing is to fill in the APPID of your own project. The back-end service selects applet cloud development and
Insert picture description here
clicks the new button. Can create projects for cloud development. The
Insert picture description here
overall function of the interface is relatively clear, divided into navigation bar, simulator on the left, and code manager on the right
Insert picture description here
The cloud development of the navigation bar is equivalent to the background entrance of database management. Click to enter the management interface to create a collection to add records, and at the same time, you can manage the attachments uploaded by the applet. The compiler can clear the cache and choose which page to compile. The function of the simulator is to display the effect of the program on the mobile phone after running, and the code manager manages the codes of different business modules in the form of folders.
Insert picture description here
The code manager is divided into two parts, front-end code and back-end code. The front-end code is placed in the miniprogram folder, and the back-end code is placed in the cloudfunctions folder.
This tutorial is a practical tutorial, and a practical small project will be used to explain how to use cloud development technology to develop a small program.

demand analysis

Project background
The initiator of the project is a senior practitioner who has been engaged in the education industry for a long time. In order to meet the needs of parents to quickly find a suitable teacher for one-on-one tutoring, there is a need to build a tutoring platform, so the project needs are put forward.
Parent needs The
home page is used to introduce the purpose of the "Famous Teacher Hui➸Tutor Help" Mini Program. The specific content is as follows, you can use a static HTML to compile the following content:
Peiyou Master: You can display the subjects of the subject according to the nine-square grid, click on the subject to list all teachers under that subject, and then click on the teacher name to see the detailed information of the teacher .
Ask for tutors quickly. Parents can publish their appointment information, fill in their own requirements and actual location, so that the platform can match the appropriate teacher.
The function of platform management The function of
teacher management: you can maintain teacher information and publish it to the Peiyou Famous Teacher column.
The function of appointment management: you can view the latest appointment information, and the list should distinguish which information has been viewed.

Database Design

Through demand analysis, three tables are designed in general, one is the permission table, and the administrator’s openid is added in it so that it can be distinguished on the mobile phone as an administrator or an ordinary parent. The second table is a teacher table designed to meet the needs of parents to browse information and administrators to maintain information. The third table is an appointment information form designed to record the appointment content submitted by parents.
Authority table (admin)
Insert picture description here
teacher table (teacher)
Insert picture description here
reservation table (subscribe)
Insert picture description here

Overall architecture

To compile the project, after reading the requirements and completing the database design, the next step is to consider the technical architecture, what architecture to use for the front end, and what architecture to use for the back end. Here we use WeChat’s native front-end framework weui for the front end, and we use the back end. Cloud function. The advantage is that all the WeChat framework is used to build it, eliminating the trouble of not integrating various technologies, and the development efficiency is relatively high.
How to build weui
Log in to the WeChat official account platform, click on the document column and
Insert picture description here
click on the extension capabilities to see
Insert picture description here
the very detailed introduction in the component library of weui. The problem encountered by beginners is that npm will not be installed. The specific installation method is to open the development tool. Right-click the miniprogram and choose to open it
Insert picture description here
in the terminal. In the terminal, execute npm init
Insert picture description here
npm init install
Insert picture description here
npm install weui-miniprogram and
Insert picture description here
then check the use of npm module
Insert picture description here
in the details of the development tool, and then select build npm in the toolbar.
Insert picture description here
After the successful build, there is an additional miniprogram_npm The directory represents success.
Insert picture description here
After the build is completed, you need to add @import'miniprogram_npm
/weui-miniprogram/weui-wxss/dist/style/weui.wxss' in the first line of app.wxss; so that weui can use
PS normally : if It prompts that npm is not an internal or external command, indicating that nodejs is not installed on your computer, just download the latest version and install it yourself.

Home

Insert picture description here
The homepage is basically for displaying information. At first, we considered using the richtext component of WeChat to develop, but the content of the homepage was changed. Every time the content was adjusted, it had to be changed in js for a long time, and later changed to the article component.

wxml code

<view class="page">
  <view class="page__hd">
    <view class="weui-article">
      <view class="weui-article__h1 h1_center"><text class="bgindent">名师帮帮</text></view>
    </view>
    <view class="weui-article__section">
      <view class="weui-article__h2 title">概述</view>
      <view class="weui-article__section">
        <view class="weui-article__p p_indent">
          <text class="bgindent">“名师帮帮”</text>何老师从事教学工作二十多年,积累了丰富的教学经验和大量的教师资源,同时也感受到家长、学生的需求与资源匮乏之间的矛盾,希望可以借助该平台在学生和老师之间搭建起一座桥梁。
        </view>
      </view>
      <view class="weui-article__h2 title">教师资质</view>
      <view class="weui-article__section">
        <view class="weui-article__p p_indent">
        <text class="bgindent">“名师帮帮”</text>确认的所有老师都是<text class="green">专职的优秀老师</text>(包括一线在职老师和自由老师),均具有丰富的教学经验,<text class="green">验证过辅导成绩证明</text>,分为:
        </view>
        <view class="weui-article__p p_indent">
        1)<text class="green">培优名师</text>:带出过考入清华北大、获得国内国际竞赛大奖或者班级第一名学生的老师。
        </view>
        <view class="weui-article__p p_indent">
         2)<text class="green">补差名师</text>:辅导后孩子单科学习成绩提高三十分以上的老师。
        </view>
      </view>
      <view class="weui-article__h2 title">运行机制</view>
      <view class="weui-article__section">
        <view class="weui-article__p p_indent">
          <text class="bgindent">“名师帮帮”</text>的运行机制如下:
          <view>
          1). 家长提供学生的学习情况,由何老师推荐适合的最佳老师;
          </view>
          <view>
          2). 上课方式可以到家上课,也可双方协商;
          </view>
          <view>
          3). 课费一次一付给上课老师;
          </view>
          <view>
          4). 何老师负责跟踪教学过程,协助家长和学生解决问题。
          </view>
        </view>
      </view>
      <view class="weui-article__h2 title">课费标准</view>
      <view class="weui-article__section">
        <view class="weui-article__p p_indent">
          <text class="bgindent">“名师帮帮”</text>的老师课时(1小时)费用范围为 300~1000元,具体课费根据年级、科目以及上课时间商议而定。
        </view>
      </view>
      <view class="weui-article__h2 title bgindent">联系人:何老师</view>
      <view class="weui-article__section">
        <view class="weui-article__p">
          1) <text class="green">电话</text>:  
          <view>
          (周一至周五10:00-15:00可电话,其余时间请微信)
          </view>
          <view>
          2) <text class="green">微信</text>:
          </view>
        </view>
      
      </view>
    </view>
  </view>
</view>

wxss

page {
  background: #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding:5px;
  color:#128b68;
}
.bg{
  padding-right:10px;
}
.h1_center{
  text-align: center;
  
}
.bgindent{
  background: linear-gradient(to right,#005343,#60501d,#802e00,#82181c);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}
.green{
  color:#43853b;
  font-weight:bold;
}
.weui-article{
  padding-top:0px;
  padding-bottom:0px;
}
.p_indent{
  text-indent: 2em;
}
.title{
  border-left: 3px solid #c60;
  padding-left:15px;
  text-shadow: #f7bc9c 1px 0 10px;
}

Navigation page

Insert picture description here
The instructor quick check mainly shows the subjects that can be trained. There are currently nine subjects. Click on a subject to jump to the teacher list of the corresponding subject. Here we use the nine-square grid layout of weui, which is tied to each category in the wxml page. Specify the category name, and pass the category name when jumping to the list page

WXML

<view class="page">
    <view class="page__hd">
        <view class="page__title"><text class="bgindent">教员速查</text></view>
    </view>
    <view class="page__bd">
        <view class="weui-grids">
            <block wx:for="{
   
   {classes}}" wx:key="*this">
                <navigator url="../teacherlist/teacherlist?name={
   
   {item}}&type=0" class="weui-grid" hover-class="weui-grid_active">
                    <image class="weui-grid__icon" src="/images/class-0{
   
   {index+1}}.png" />
                    <view wx:if="{
   
   {index==0||index==1||index==2||index==6||index==7||index==8}}" class="weui-grid__label blue">{
   
   {item}}</view>
                    <view  wx:if="{
   
   {index==3||index==4||index==5}}" class="weui-grid__label green">{
   
   {item}}</view>
                </navigator>
            </block>
        </view>
    </view>
</view>

WXSS

page{
  background: #ffffff;
}
.title{
  padding:20px;
  color:#F8AD00
}
.item{
  width:100px;
  text-align: center;
  margin-top:25px;
}
.wrap{
  flex-wrap:wrap
}
.bgindent{
  background: linear-gradient(to right,#005343,#60501d,#802e00,#82181c);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}
.green{
  color:#43853b;
  font-weight:bold;
}
.blue{
  color:#128b68;
  font-weight:bold;
}

js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    classes: ['语文', '数学', '英语', '历史', '地理', '政治', '化学', '物理','生物']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

Teacher list page

Insert picture description here
The teacher list page needs to query the qualified teachers from the database to display on the page, click the teacher’s name to jump to the details page

wxml

<view class="page">
  <view class="page__bd">
    <view class="weui-panel weui-panel_access">
      <view class="weui-panel__hd"><text class="bgindent">名师汇</text></view>
      <view class="weui-panel__bd">
        <view class="weui-media-box weui-media-box_text" wx:for="{
   
   {teacherlist}}">
          <navigator url="../teacherdetail/teacherdetail?id={
   
   {item._id}}">
            <view class="weui-media-box__title weui-media-box__title_in-text"><text class="blue">{
   
   {item.name}}</text> <text class="blue margin25">编号:</text><text class="green">{
   
   {item.no}}</text></view>
            <view class="weui-media-box__desc"><text class="blue">科目:</text> <text class="green">{
   
   {item.course}}</text> <text class="blue margin20">性别:</text><text class="green">{
   
   {item.sex}} </text><text class="blue margin20">教龄:</text><text class="green">{
   
   {item.year}}</text></view>
          </navigator>
        </view>
        <view wx:if="{
   
   {teacherlist.length==0}}" style="text-align:center;line-height:20px;font-size:16px;padding-top:25px;padding-bottom:25px">
     <text class="blue">该类别下暂无教师</text>
  </view>
      </view>
    </view>
  </view>
</view>

wxss

.margin20{
  margin-left: 20px;
}
.margin25{
  margin-left: 27px;
}

js

// miniprogram/pages/teacherlist/teacherlist.js
wx.cloud.init()
const db = wx.cloud.database()
const teacherCollection = db.collection('teacher')
const _ = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    teacherlist:[],
    type:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.name+" "+options.type)
    console.log(teacherCollection)
    teacherCollection.where({
      course:options.name,
    }).get().then(res => {
        console.log(res.data)
      this.setData({
        teacherlist: res.data,
        type:options.type
      })
      })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

Teacher Details Page

Insert picture description here
The details page is relatively simple. Receive the ID parameter passed in from the page, and then go to the database to get the teacher’s information and display it on the page.

wxml

<view class="page">
    <view class="page__bd">
<view class="weui-cells weui-cells_after-title">
            <view class="weui-cell">
                <view class="weui-cell__bd"><text class="blue">姓名</text></view>
                <view class="weui-cell__ft"><text class="green">{
   
   {teacher.name}}</text></view>
            </view>
            <view class="weui-cell">
                <view class="weui-cell__bd"><text class="blue">编号</text></view>
                <view class="weui-cell__ft"><text class="green">{
   
   {teacher.no}}</text></view>
            </view>
            <view class="weui-cell">
                <view class="weui-cell__bd"><text class="blue">科目</text></view>
                <view class="weui-cell__ft"><text class="green">{
   
   {teacher.course}}</text></view>
            </view>
            <view class="weui-cell">
                <view class="weui-cell__bd"><text class="blue">性别</text></view>
                <view class="weui-cell__ft"><text class="green">{
   
   {teacher.sex}}</text></view>
            </view>
            <view class="weui-cell">
                <view class="weui-cell__bd"><text class="blue">教龄(年)</text></view>
                <view class="weui-cell__ft"><text class="green">{
   
   {teacher.year}}</text></view>
            </view>
            <view class="weui-cell">
                <view class="weui-cell__bd"><text class="blue">可辅导年级</text></view>
                <view class="weui-cell__ft"><text class="green">{
   
   {teacher.grade}}</text></view>
            </view>
            <view class="weui-cell flex">
                <view class="weui-cell__bd left" style="width:100%"><text class="blue">过往辅导成绩</text></view>
                <view class="weui-cell__ft left" style="width:100%"><text class="green">{
   
   {teacher.score}}</text></view>
            </view>
            <view class="weui-cell">
                <view class="weui-cell__bd"><text class="blue">课时费</text></view>
                <view class="weui-cell__ft"><text class="green">{
   
   {teacher.cost}}</text></view>
            </view>
        </view>

    </view>
</view>

wxss

.flex{
  flex-direction: column;
  
}
.left{
text-align: left;
}

js

wx.cloud.init()
const db = wx.cloud.database()
const teacherCollection = db.collection('teacher')
const _ = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: { 
    teacher:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.id)
     teacherCollection.doc(options.id).get({
      success: res => {
        console.log(res.data)
        this.setData({
          teacher:res.data
        })
      }
     })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getUserInfo: function (result) {
    console.log("111")
    wx.redirectTo({
      url: '../order/order',
    })
  }
})

My page

Insert picture description here
My page is relatively complicated, because the first step is to solve the login problem. WeChat adds attributes through the button component to support login after clicking the button. When the login information is obtained, it is necessary to obtain whether the user is an administrator, if not, then You can’t see the functions of teacher management and appointment management in the menu below. If you are an administrator, you can maintain the teacher and process the appointment information. Of course, you must write cloud functions to achieve these functions, because the code on the small terminal cannot be completed. of.

wxml

<view class="container">
  <view class="page-body">
    <view class="page-section">
      <view class="page-section-spacing">
        <view style="flex-direction:row;width:100%;">
        <block wx:if="{
   
   {userInfo.nickName}}">
        <view class="flex-item"><image class="userinfo-avatar" src="{
   
   {userInfo.avatarUrl}}" background-size="cover"></image>{
   
   {Object.keys(userInfo).length}}</view>
          <view style="text-align:center;margin-bottom:5px">{
   
   {userInfo.nickName}}</view>
          </block>
    <block wx:else>
    <view class="flex-item"><image class="userinfo-avatar" src="../../images/user-unlogin.png" background-size="cover"></image></view>
          <view style="text-align:center;margin-bottom:5px"><button open-type="getUserInfo" lang="zh_CN" size="mini" type="primary" bindgetuserinfo="onGotUserInfo">登录{
   
   {Object.keys(userInfo).length}}</button></view>
    </block>
          <mp-cells title="">
            <mp-cell link url="../orderlist/orderlist" hover value="我的预约" footer="" ext-class="green">
                <image slot="title" src="../../images/dingdan.png" style="margin-right: 16px;vertical-align: middle;width:20px; height: 20px;"></image>
            </mp-cell>
            <mp-cell link url="../order/order" hover value="快速预约" footer="" ext-class="green">
                <image slot="title" src="../../images/yuyue.png" style="margin-right: 16px;vertical-align: middle;width:20px; height: 20px;"></image>
            </mp-cell>
            <mp-cell wx:if="{
   
   {userInfo.isadmin==1}}" link url="../teachermanage/teachermanage" hover value="教师管理" footer="" ext-class="blue">
                <image slot="title" src="../../images/jiaoshiguanli.png" style="margin-right: 16px;vertical-align: middle;width:20px; height: 20px;"></image>
            </mp-cell>
            <mp-cell wx:if="{
   
   {userInfo.isadmin==1}}" link url="../ordermanage/ordermanage" hover value="预约管理" footer="" ext-class="blue">
                <image slot="title" src="../../images/jiazhang.png" style="margin-right: 16px;vertical-align: middle;width:20px; height: 20px;"></image>
            </mp-cell>
        </mp-cells>
        </view>
      </view>
    </view>
  </view>
</view>

wxss

.container{
  background: #ffffff;
  width:100%;
  
}
.page-body{
  width:100%;
}
.flex-item{
  text-align: center;
  width:325px;
}

js

// miniprogram/pages/my/my.js
const db = wx.cloud.database()
const admin = db.collection('admin')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
    const userInfo = app.globalData.userInfo
    if (userInfo) {
    admin.where({
      openid:userInfo.openid
    }).count().then(res => {
      userInfo.isadmin = res.total
      
        this.setData({
          userInfo: userInfo
        })
     
    })
      .catch(err => {
        console.error(err)
      })
  }
    
   
    /*wx.getSetting({
      success: res => {
        console.log("-----" + res.authSetting['scope.userInfo'])
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          console.log("已授权" + res.authSetting['scope.userInfo'])
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
              console.log(Object.keys(this.data.userInfo).length)
            }
          })
        }
      }
    })*/
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const userInfo = app.globalData.userInfo
    if (userInfo) {
    admin.where({
      openid: userInfo.openid
    }).count().then(res => {
        userInfo.isadmin = res.total
        this.setData({
          userInfo: userInfo
        })
      
    })
      .catch(err => {
        console.error(err)
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const userInfo = app.globalData.userInfo
    if (userInfo) {
      admin.where({
        openid: userInfo.openid
      }).count().then(res => {
        userInfo.isadmin = res.total
        this.setData({
          userInfo: userInfo
        })

      })
        .catch(err => {
          console.error(err)
        })
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onGotUserInfo: function (result) {
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        console.log(res.result.dbResult.total)
        result.detail.userInfo.openid = res.result.OPENID
        result.detail.userInfo.isadmin = res.result.dbResult.total
        app.globalData.userInfo = result.detail.userInfo
        this.setData({
          userInfo: result.detail.userInfo
        })
        wx.setStorageSync("userInfo", result.detail.userInfo)
      }
    })
  }
})

Insert picture description here
The reservation list page mainly queries the records from the database. When the reservation information is viewed, the status is updated at the same time, and the status is changed to read

wxml

<view class="page">
    <view class="page__bd">
        <mp-cells ext-class="my-cells" title="预约列表">
        <block wx:for="{
   
   {subscribe}}">
        <navigator url="../orderdetail/orderdetail?id={
   
   {item._id}}&flag=1">
             <block wx:if="{
   
   {item.status=='0'}}">
                <mp-cell ext-class="blue" value="预约科目:{
   
   {item.class}}[未读]" footer="{
   
   {item.createtime}}"></mp-cell>
              </block>
              <block wx:if="{
   
   {item.status=='1'}}">
                 <mp-cell ext-class="green" wx:if="{
   
   {item.status==='1'}}" value="预约科目:{
   
   {item.class}}[已读]" footer="{
   
   {item.createtime}}"></mp-cell>
                </block>
              
                </navigator>
          </block>
        </mp-cells>
    </view>
</view>

json

{
  "usingComponents": {
    "mp-cells": "../components/cells/cells",
    "mp-cell": "../components/cell/cell",
    "mp-slideview": "../components/slideview/slideview"
  }
}

wxss

/* miniprogram/pages/ordermanage/ordermanage.wxss */
.weui-cell__ft{
color:#43853b!important;
} 
.weui-cells__title{
  color:#43853b;
}

js

wx.cloud.init()
const db = wx.cloud.database()
const subscribeCollection = db.collection('subscribe')
const _ = db.command
const app = getApp();
Page({
  data: {
    subcribe: {}
  },
  onLoad: function () {
    
    subscribeCollection.orderBy('createtime', 'desc').get().then(res => {
      for (var index in res.data) {
        var time = res.data[index].createtime;
        console.log(time)
        res.data[index].createtime = time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate()
      }

      this.setData({
        subscribe: res.data,
      })
    })
    this.setData({
      slideButtons: [{
        type: 'warn',
        text: '删除',
        extClass: 'test',
        src: '/page/weui/cell/icon_del.svg', // icon的路径
      }],
    });
  },
  onShow(){
    subscribeCollection.orderBy('createtime', 'desc').get().then(res => {
      for (var index in res.data) {
        var time = res.data[index].createtime;
        console.log(time)
        res.data[index].createtime = time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate()
      }

      this.setData({
        subscribe: res.data,
      })
    })
  },
  slideButtonTap(e) {
    console.log('slide button tap', e.detail)
  }
});

Insert picture description here
The new appointment page uses the extension component of weui, mainly using the form, which can be easily verified

wxml

<mp-toptips msg="{
   
   {error}}" type="error" show="{
   
   {error}}"></mp-toptips>
<view class="page" xmlns:wx="http://www.w3.org/1999/xhtml">
    <view class="page__bd">
        <mp-form id="form" rules="{
   
   {rules}}" models="{
   
   {formData}}">
            <mp-cells class="green" title="快速预约家教">
                <mp-cell prop="class" title="辅导科目" ext-class="blue">
                    <input bindinput="formInputChange" data-field="class" placeholder-class="green" class="weui-input green" placeholder="请输入辅导科目"/>
                </mp-cell>
                <mp-cell prop="grade" title="辅导年级" ext-class="blue">
                    <input bindinput="formInputChange" data-field="grade" placeholder-class="green" class="weui-input green" placeholder="请输入辅导年级"/>
                </mp-cell>
                <mp-cell prop="contactname" title="联系人姓名" ext-class="blue">
                    <input bindinput="formInputChange" data-field="contactname" placeholder-class="green" class="weui-input green" placeholder="请输入联系人姓名"/>
                </mp-cell>
                <mp-cell prop="telphone" title="手机号" ext-class="blue">
                    <input placeholder-class="green" bindinput="formInputChange" data-field="telphone" class="weui-input green" placeholder="请输入手机号"/>
                </mp-cell>
                <mp-cell  title="微信号" ext-class="blue">
                    <input placeholder-class="green" bindinput="formInputChange" data-field="microno" class="weui-input green" placeholder="请输入微信号"/>
                </mp-cell>
            </mp-cells>
            <view class="weui-cells__title blue">地址</view>
        <view class="weui-cells weui-cells_after-title">
            <view class="weui-cell">
                <view class="weui-cell__bd">
                    <input placeholder-class="green" class="weui-input green" bindinput="formInputChange" placeholder="填写辅导的详细地址" data-field="address"/>
                </view>
            </view>
        </view>

        <view class="weui-cells__title blue">要求</view>
        <view class="weui-cells weui-cells_after-title">
            <view class="weui-cell">
                <view class="weui-cell__bd">
                    <textarea placeholder-class="green" data-field="demand" bindinput="formInputChange" class="weui-textarea green"  placeholder="填写您对辅导老师的具体要求" style="height: 3.3em" />
                </view>
            </view>
        </view>
        <view class="weui-btn-area">
            <button class="weui-btn" type="primary" bindtap="submitForm">提交</button>
        </view>
        </mp-form>
        
    </view>
</view>

wxss

/* miniprogram/pages/order/order.wxss */
.weui-cells__title{
   color:#43853b;
}

js

wx.cloud.init()
const db = wx.cloud.database()
const orderCollection = db.collection('subscribe')
const _ = db.command
Component({
  data: {
    showTopTips: false,
    formData: {
    },
    rules: [{
      name: 'class',
      rules: { required: true, message: '辅导科目是必选项' },
    }, {
        name: 'grade',
        rules: { required: true, message: '辅导年级是必选项' },
      }, {
        name: 'contactname',
        rules: { required: true, message: '联系人姓名是必选项' },
      }, {
        name: 'telphone',
        rules: [{ required: true, message: '手机号必填' }, { mobile: true, message: '手机号格式不对' }],
      }, {
        name: 'microno',
        rules: { required: true, message: '微信号是必选项' },
      }]
  },
  methods: {
    formInputChange(e) {
      const { field } = e.currentTarget.dataset
      this.setData({
        [`formData.${field}`]: e.detail.value
      })
    },
    submitForm() {
      this.selectComponent('#form').validate((valid, errors) => {
        console.log('valid', valid, errors)
        if (!valid) {
          const firstError = Object.keys(errors)
          if (firstError.length) {
            this.setData({
              error: errors[firstError[0]].message
            })

          }
        } else {
          console.log(this.data.formData)
          var address ="";
          var demand = ""; 
            if(this.data.formData.hasOwnProperty('address')){
            address = this.data.formData.address;
            console.log(address)
          }
          if (this.data.formData.hasOwnProperty('demand')){
            demand = this.data.formData.demand;
          }
          orderCollection.add({
            // data 字段表示需新增的 JSON 数据
            data:{
              class:this.data.formData.class,
              grade:this.data.formData.grade,
              contactname:this.data.formData.contactname,
              telphone:this.data.formData.telphone,
              microno:this.data.formData.microno,
              address:address,
              demand:demand,
              createtime: new Date(),
              status:0
            }
          })
            .then(res => {
              console.log(res)
              wx.showToast({
                title: '预约成功',
                icon: 'success',
                duration: 2000
              })
              wx.switchTab({
                url: '../my/my',
              })
            })
            .catch(console.error)
        }
      })
    }

  }
});

json

{
  "usingComponents": {
    "mp-toptips": "../components/toptips/toptips",
    "mp-cells": "../components/cells/cells",
    "mp-cell": "../components/cell/cell",
    "mp-checkbox": "../components/checkbox/checkbox",
    "mp-checkbox-group": "../components/checkbox-group/checkbox-group",
    "mp-form": "../components/form/form"
  }
}

Course summary

This course demonstrates how to use the technology developed by WeChat Cloud to develop a small program through a practical case. In general, the development of WeChat small program cloud is very fast and easy to use, and it saves a lot of time without deploying a server. The most important one is especially suitable for personal development. One person can meet the common needs in daily business and realize the rapid migration of small, medium and micro enterprises to the cloud. Let's quickly experiment.
The project source code
https://gitee.com/tuodagitee/famous-teacher-help.git
online address, please search for the help of the famous teacher in the WeChat applet to see the final result

Guess you like

Origin blog.csdn.net/u012877217/article/details/104415774