Create a small program

1. Create an empty folder anywhere

2. Open the wechat small program development tool, create a project, and select Cloud development

Second, copy the files written in the previous wechat mini program development into this folder, including page, tabs, app.json, and solve the error reported after overwriting. Delete some unused things, such as interfaces, because cloud development directly calls the database. No longer need to open wx-database.json file in CMD (json-server –watch database.json)

Import database

  • 1. Click to enter cloud development

  • 2. Copy the environment ID to app.js

  • 3. Set permissions

  • 4. Import data
    • 1. Create a collection

– 2. Import data

Import successful:

Iv. Cloud development data operation and cloud function operation (Home page)

1. Create cloud functions in the ClouFunctions folder and write the cloud function entry file in the JS file

// Cloud function entry file
const cloud = require('wx-server-sdk')

cloud.init()
const db=cloud.database()
// Cloud function entry function
exports.main = async (event, context) => {
  // const wxContext = cloud.getWXContext()
  const res=await db.collection('slides').get()

  return {
    res
    // event,
    // openid: wxContext.OPENID,
    // appid: wxContext.APPID,
    // unionid: wxContext.UNIONID,}}Copy the code
// Cloud function entry file
const cloud = require('wx-server-sdk')

cloud.init()
const db=cloud.database()
// Cloud function entry function
exports.main = async (event, context) => {
  // const wxContext = cloud.getWXContext()
  const res=await db.collection('categroies').get()

  return {
    res
    // event,
    // openid: wxContext.OPENID,
    // appid: wxContext.APPID,
    // unionid: wxContext.UNIONID,}}Copy the code
  • Cloudfunctions need to be uploaded and deployed after each edit (right-click the function folder to select the third, cloud installation dependencies) and synchronize the list of cloudfunctions in cloudfunctions

2. Use cloud functions in home.js


Page({

  /** * initial data for the page */
  data: {
    slides: [].cates: []},/** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    this.getSilides()
    this.getCategories()
  },
  getSilides() {
   wx.cloud.callFunction({
     name:'get_slides'
   }).then(res= >{
     this.setData({
       slides:res.result.res.data
     })
   })
  },
  getCategories(){
    wx.cloud.callFunction({
      name:'get_categroies'
    }).then(res= >{
      this.setData({
        cates:res.result.res.data
      })
    })
  },
  goDetail(e){
    console.log(e);
    wx.navigateTo({
      url: "/pages/list/list? id="+e.target.dataset.id
    })
  },
  /** * lifecycle function - listen for the page to complete the first rendering */
  onReady: function () {},/** * lifecycle function -- listens for page display */
  onShow: function () {
    if (this.getTabBar() && typeof this.getTabBar === 'function') {
      this.getTabBar().setData({
        active: 0})}},/** * life cycle function - listen for page hiding */
  onHide: function () {},/** * life cycle function - listen for page unload */
  onUnload: function () {},/** * page-related event handlers -- listen for user pull actions */
  onPullDownRefresh: function () {},/** * the handler for the pull-down event on the page */
  onReachBottom: function () {},/** * Users click on the upper right corner to share */
  onShareAppMessage: function () {}})Copy the code

3. Render to page

  • home.json
{
  "usingComponents": {
    "van-grid": "/weapp/weapp/dist/grid/index"."van-grid-item": "/weapp/weapp/dist/grid-item/index"}}Copy the code
  • home.wxml
<view class="home"> <! -- Multicast map area --><swiper class="my-swiper" indicator-dots="{{true}}" autoplay="{{true}}">
    <swiper-item wx:for="{{slides}}" wx:key="index">
      <! -- Block does only logical judgment and does not render DOM -->
      <block wx:if="{{item.link}}">
        <navigator url="/pages/list/list">
          <image src="{{item.image}}" mode="aspectFill" />
        </navigator>
      </block>
      <block wx:else>
        <image src="{{item.image}}"  mode="aspectFill" />
      </block>
    </swiper-item>
  </swiper>

  <van-grid column-num="3">
    <van-grid-item wx:key="index" icon="{{item.icon}}" text="{{item.name}}" wx:for="{{ cates }}" url="/pages/list/list? id={{item.id}}"/>
  </van-grid>
</view>
Copy the code

Go to the list page

  • 1.home.wxml
 <van-grid column-num="3">
    <van-grid-item wx:key="index" icon="{{item.icon}}" text="{{item.name}}" wx:for="{{ cates }}" url="/pages/list/list? id={{item.id}}"/>
  </van-grid>
Copy the code
  • 2. Cloud function
    • get_categories_id
// Cloud function entry file
const cloud = require('wx-server-sdk')

cloud.init()
const db=cloud.database()
// Cloud function entry function
exports.main = async (event, context) => {
  // const wxContext = cloud.getWXContext()
  const res=await db.collection('categroies')
  .where({
    id:event.id
  })
  .get()

  return {
    res
    // event,
    // openid: wxContext.OPENID,
    // appid: wxContext.APPID,
    // unionid: wxContext.UNIONID,}}Copy the code
  • get_shops
    // Cloud function entry file
const cloud = require('wx-server-sdk')

cloud.init()
const db=cloud.database()
// Cloud function entry function
exports.main = async (event, context) => {
  // const wxContext = cloud.getWXContext()
  const res=await db.collection('shops')
  .where({
    categoryId:event.id
  })
  .skip((event.pageNo-1)*event.pageSize)
  .limit(event.pageSize)
  .get()

  return {
    res
    // event,
    // openid: wxContext.OPENID,
    // appid: wxContext.APPID,
    // unionid: wxContext.UNIONID,}}Copy the code
  • 3. Use cloud functions to obtain data

list.js

Page({

  /** * initial data for the page */
  data: {
    id:0.pageNo:0.pageSize:10.shops: [].hasMore:false
  },

  /** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    // console.log(options.id);
    // this.getCategoryById(options.id)
    this.setData({
      id:Number(options.id)
    })
    this.getCategoryById()
    this.getShops()
  },
  // Get classified content by id
  getCategoryById(){
    wx.cloud.callFunction({
      name:'get_categroies_id'.data: {id:this.data.id
      }
    }).then(res= >{
      wx.setNavigationBarTitle({
        title: res.result.res.data[0].name,
      })
    })
  },
  // Get the goods
 async getShops(){
    / / throttling
    if(this.data.hasMore! = =false) return 
    ++this.data.pageNo
  const res=await wx.cloud.callFunction({
      name:'get_shops'.data: {id:this.data.id,
        pageNo:this.data.pageNo,
        pageSize:this.data.pageSize
      }
    })
     if(res.result.res.data.length>0) {this.setData({
        shops:this.data.shops.concat(res.result.res.data)
      })
     }else {
       this.setData({
         hasMore:true})}},// Load more
  getMore() {
    this.getShops()
  },
  // Make a simulated phone call
  makePhoneCall(e){
    wx.makePhoneCall({
      phoneNumber: e.target.dataset.phone // This is an example, not a real phone number})},/** * lifecycle function - listen for the page to complete the first rendering */
  onReady: function () {},/** * lifecycle function -- listens for page display */
  onShow: function () {},/** * life cycle function - listen for page hiding */
  onHide: function () {},/** * life cycle function - listen for page unload */
  onUnload: function () {},/** * page-related event handlers -- listen for user pull actions */
  onPullDownRefresh:async function () {
   await this.setData({
      pageNo:0.shops: [].hasMore:false
    })
   await this.getShops()
    wx.stopPullDownRefresh()// Stop the current page pull-down refresh
  },

  /** * the handler for the pull-down event on the page */
  onReachBottom: function () {
    // Drop down to load more items
    this.getMore()
  },

  /** * Users click on the upper right corner to share */
  onShareAppMessage: function () {}})Copy the code
  • 4. Render to page

list.json

{
  "usingComponents": {
    "van-card": "/weapp/weapp/dist/card/index"
  },
  "enablePullDownRefresh":true."backgroundColor":"# 000"
}
Copy the code

list.wxml

<view class="list">
  <van-card
    wx:for="{{shops}}"
    wx:key="index"
    tag="{{item.score}}"
    title="{{item.name}}"
    thumb="{{ item.images[0] }}"
  >
    <view slot="desc">
     <view bindtap="makePhoneCall" data-phone="{{item.phone}}">Contact number: {{item.phone}}</view>
     <view>Address: {{item.address}}</view>
     <view>BusinessHours: {{item.businessHours}}</view>
     <view>Facilities: {{item. SupportService}}</view>
    </view>
  </van-card>
  <view wx:if="{{! hasMore}}" class="loadmore loading">Loading...</view>
  <view wx:else class="loadmore">There's no more to it</view>
</view>
Copy the code

list.wxss

.loadmore {
  color: #888;
  font-size: 30rpx;
  line-height: 100rpx;
  text-align: center;
}

.loadmore.loading::before {
  content: ' ';
  width: 40rpx;
  height: 40rpx;
  margin-top: -10rpx;
  margin-right: 10rpx;
  display: inline-block;
  vertical-align: middle;
  animation: loading 1s steps(12) infinite; background: transparent url(data:image/svg+xml; base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgMTAwIDEwM CI+PHBhdGggZmlsbD0ibm9uZSIgZD0iTTAgMGgxMDB2MTAwSDB6Ii8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsP SIjRTlFOUU5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTMwKSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41I iB5PSI0MCIgZmlsbD0iIz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JtPSJyb3RhdGUoLTEyMCA0MS4zNCA2N SkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNEMkQyRDIiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb 3RhdGUoLTkwIDM1IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0RBREFEQSIgcng9IjUiIHJ5PSI1I iB0cmFuc2Zvcm09InJvdGF0ZSgtNjAgMjQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTJFM kUyIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKC0zMCAtNS45OCA2NSkiLz48L3N2Zz4=) no-repeat; background-size:100%
}

@keyframes loading {
  from {
    transform: rotate(0deg)
  }
  to {
    transform: rotate(-360deg)
  }
}
Copy the code

6. Authorized login

1. Create the login page

2. Find the user information in the documents of wechat public platform, and copy the example to login. WXML and login.js

login.wxml

<! --<view class="container">
  <view class="userinfo">
    <block wx:if="{{! hasUserInfo}}">
      <button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile">Get avatar nickname</button>
      <button wx:else open-type="getUserInfo" bindgetuserinfo="getUserInfo">Get avatar nickname</button>
    </block>
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
</view> -->

<view class="userinfo">
    <block wx:if="{{! hasUserInfo}}">
      <button bindtap="getUserProfile">Login authorization</button>
    </block>
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>

Copy the code

login.js

const db=wx.cloud.database()
Page({
  data: {
    userInfo: {},
    hasUserInfo: false.canIUseGetUserProfile: false,},onLoad() {
    // if (wx.getUserProfile) {
    // this.setData({
    // canIUseGetUserProfile: true
    / /})
    // }
    const state=wx.getStorageSync('state')
    const userInfo=JSON.parse(wx.getStorageSync('userInfo') | |'{}')
    if(! state){this.setData({
        hasUserInfo:true,
        userInfo
      })
    }
  },
  getUserProfile(e) {
    Wx.getuserprofile is recommended to obtain user information. Every time the developer obtains user information through this interface, the user must confirm
    // The developer keeps the avatar nicknames quickly filled in by the user to avoid repeated pop-ups
    wx.getUserProfile({
      desc: 'To improve member information'.// Specify the purpose of obtaining the user's personal information, which will be displayed in the subsequent pop-up window
      success: (res) = > {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        // console.log("success");
        db.collection('user').add({
          data: {phone:'18888888888'
          }
        }).then(res= >{
          console.log(res);
        })
        wx.setStorageSync('state'.'state')
        wx.setStorageSync('userInfo'.JSON.stringify(res.userInfo))
        setTimeout(() = >{
          wx.switchTab({
            url: '/pages/home/home',},3000)})}})},getUserInfo(e) {
    GetUserInfo is not recommended for obtaining user information. It is expected that from April 13, 2021, getUserInfo will no longer pop up and directly return anonymous user information
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true})}})Copy the code

3. Create data set User

4. In login.js, use the add mode in user to save data to memory

const db=wx.cloud.database()



    const state=wx.getStorageSync('state')
    const userInfo=JSON.parse(wx.getStorageSync('userInfo') | |'{}')
    
    
    
     db.collection('user').add({
        data: {phone:'18888888888'
        }
     }).then(res= >{
        console.log(res);
       })
     wx.setStorageSync('state'.'state')
     wx.setStorageSync('userInfo'.JSON.stringify(res.userInfo))
     setTimeout(() = >{
        wx.switchTab({
           url: '/pages/home/home',},3000)})Copy the code

7. Login interception

  • If state exists in memory, it will not be intercepted. If state does not exist, the login page is displayed for login

app.json

 const state=wx.getStorageSync('state')
      if(! state){ wx.redirectTo({url: '/pages/login/login'})},Copy the code
//app.js
App({
  onLaunch: function () {
    if(! wx.cloud) {console.error('Please use base library 2.2.3 or above to use cloud capabilities')}else {
      wx.cloud.init({
        // env
        The // env argument determines which cloud environment resources will be requested by default by the next cloud development call (wx.cloud.xxx) made by the applet
        // Enter the environment ID. You can view the environment ID on the cloud console
        // If not, use the default environment (the environment created first).
        env: 'cloud1-6givj2tua364b003'.traceUser: true,})const state=wx.getStorageSync('state')
      if(! state){ wx.redirectTo({url: '/pages/login/login',}}}this.globalData = {}
  }
})

Copy the code

Viii. Project launch