小程序云开发基础搭建及部署初体验

130 阅读2分钟

注册略

新建小程序

 开通云开发功能

 新建cloud文件夹

 指定云函数目录

 云服务注册

//app.js
App({
  onLaunch: function () {
    wx.cloud.init({
      env: '你的云环境ID',
      traceUser: true
    })
  }
})

新增页面

pages中新建页面目录,并新建页面

 添加images目录及tabbar图标

设置导航栏

{
  "pages": [
    "pages/index/index",
    "pages/me/me",
    "pages/list/list"
  ],
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "vczhHu",
    "navigationBarTextStyle": "black"
  },
  "tabBar": {
    "selectedColor": "#FF9900",
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "images/home.png",
        "selectedIconPath": "images/home_a.png"
      },
      {
        "pagePath": "pages/list/list",
        "text": "logs",
        "iconPath": "images/list.png",
        "selectedIconPath": "images/list_a.png"
      },
      {
        "pagePath": "pages/me/me",
        "text": "我的",
        "iconPath": "images/me.png",
        "selectedIconPath": "images/me_a.png"
      }
    ]
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json"
}

 

实现登录功能并缓存信息

登录功能在“我的”页面实现,可以将该页面路由前置方便调试

 页面实现

<!--pages/me/me.wxml-->
<view wx:if="{{!openid}}">
  <button open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="onGotUserInfo">登录</button>
</view>
<view wx:else class="me-container">
  <image class="avatar-img" src="{{userinfo.avatarUrl}}"></image>
  <view class="name">{{userinfo.nickName}}</view>
</view>

新建云函数

 

上传并部署 

 逻辑实现

// pages/me/me.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userinfo: {},
    openid: ""
  },
  onGotUserInfo: function (e) {
    const self = this
    wx.cloud.callFunction({
      name: "login",
      success: res => {
        self.setData({
          openid: res.result.openid,
          userinfo: e.detail.userInfo
        })
        self.data.userinfo.openid = self.data.openid
        wx.setStorageSync("userinfo", self.data.userinfo)
      },
      fail: res => {
        console.log('err', res.errMsg)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const userInfo = wx.getStorageSync("userinfo")
    this.setData({
      userinfo: userInfo,
      openid: userInfo.openid
    })
  }
})

生成log数据(云数据库插入)

页面实现及事件绑定

<!--index.wxml-->
<view class="container">
  <view bindtap="addLog" data-add="1">+1</view>
  <view bindtap="addLog" data-add="-1">-1</view>
</view>

云数据库新建集合

 设置云数据库权限

 新建创建log的云函数

cloud/createlog/index.js 

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { add, date, openid } = event
    return await db.collection('logs').add({
      data: {
        add,
        date,
        openid
      }
    })
  } catch (e) {
    console.log(e)
  }
}

逻辑实现

//index.js
Page({

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

  },
  addLog(e) {
    const add = e.currentTarget.dataset.add
    const userInfo = wx.getStorageSync("userinfo")
    if (!userInfo.openid) {
      wx.switchTab({
        url: '/pages/me/me',
      })
    } else {
      wx.cloud.callFunction({
        name: "createlog",
        data: {
          add,
          date: Date.now(),
          openid: userInfo.openid
        }
      })
    }
  }
})

数据获取及展示

页面实现

<!--pages/list/list.wxml-->
<block wx:for="{{logs}}" wx:key="key">
  <view>Time:{{item.date}} Content:{{item.add}}</view>
</block>

新建log获取云函数

 逻辑实现

// pages/list/list.js
const util = require('../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    logs: []
  },
  getlogs: function () {
    const self = this
    const userInfo = wx.getStorageSync("userinfo")
    if (!userInfo.openid) {
      wx.switchTab({
        url: '/pages/me/me',
      })
    } else {
      wx.cloud.callFunction({
        name: "getlogs",
        data: {
          openid: userInfo.openid
        },
        success: res => {
          self.setData({
            logs: res.result.data.map(log => {
              const date = util.formatTime(new Date(log.date))
              log.date = date
              return log
            })
          })
        },
        fail: res => {
          console.log(res.errMsg)
        }
      })
    }
  },

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