微信小程序之云开发

环境搭建

创建云开发项目

勾选上 微信云开发 输入你的AppID 然后点击确定
在这里插入图片描述
在这里插入图片描述
然后点击左上角的云开发按钮进入面板
在这里插入图片描述
你的云函数,所谓云函数,就是操作你云数据库的方法,通过对应的云函数去对你的数据库里的数据进行增删改查
在这里插入图片描述
就此云开发环境搭建完成

云开发Demo

Demo描述

Demo名称:留言板;
Demo功能需求:

  1. 能发布留言
  2. 留言显示
  3. 留言有发布用户的用户信息
  4. 留言可以附带图片,发布的时候能够上传图片
  5. 留言拥有对应时间戳
  6. 拥有翻页功能,一页只显示三条数据

Demo实现

编写云函数方法

首先,根据需求,我们需要一下的云函数进行数据库操作:

  1. getMessage 获取留言信息
  2. setMessage 添加留言信息

在cloudfunctions中创建对应的云函数文件
在这里插入图片描述
在这里插入图片描述
开始编写getMessage与setMessage对应功能。
setMessage:
在这里插入图片描述
getMessage
在这里插入图片描述

页面建立

在 项目文件里的pages中创建一个home文件
在这里插入图片描述
app.json中 将home路径调为第一个显示
在这里插入图片描述

home.wxml 代码

home.wxml

<!--pages/home/home.wxml-->
<view class="addArea">
  <textarea placeholder="请输入留言" auto-focus bindinput="inputHd" value="{{tempMsg}}"></textarea>
  <view class="buttons">
    <!-- 判断是否有用户信息 -->
    <button type="primary" class="btn" bindtap="setMessage" wx:if="{{userInfo.nickName}}">发表留言</button>
    <!-- 如果没有 则获取用户信息 再发布留言 -->
    <button type="primary" class="btn" bindtap="getUserProfile" wx:else="">发表留言</button>
    <!-- 添加上传图片按钮 -->
    <button class="plus" bindtap="upImg">+</button>
  </view>
  <!-- 判断是否有上传图片 -->
  <image src="{{tempPic}}" class="tempPic" wx:if="{{tempPic}}"></image>
</view>
<view class="message">
  <view class="msg" wx:for="{{message}}" wx:key="_id">
    <view class="avatar" wx:if="{{item.userInfo}}">
      <image src="{{item.userInfo.avatarUrl}}"></image>
      <text>{{item.userInfo.nickName}}</text>
    </view>
    <view class="content">
      <view>
        <text>{{item.content}}</text>
        <image src="{{item.pic}}" wx:if="{{item.pic}}"></image>
      </view>
      <view>
        <view class="date">{{item.date}}</view>
      </view>
    </view>
  </view>
</view>
<view class="pagination">
  <button size="mini" type="primary" plain="true" data-val="{{-1}}" wx:if="{{current>1}}" bindtap="getMessage">上一页</button>
  <button size="mini" type="primary" plain="true" data-val="{{1}}" wx:if="{{current<pagination.total/pagination.pageSize}}" bindtap="getMessage">下一页</button>
</view>

home.js 代码

home.js

// pages/home/home.js
const {
  formatTime
} = require('../../utils/utils');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    message: [], // 留言数据
    tempMsg: "", // 临时留言数据
    tempPic: '', // 临时图片
    userInfo: {}, // 用户信息
    current: 1, // 当前页码
    pagination: {}, // 分页苏剧
  },
  // 与textarea的双向绑定
  inputHd(e) {
    this.setData({
      tempMsg: e.detail.value
    })
  },
  // 上传留言
  setMessage() {
    wx.cloud.callFunction({
      // 指定云函数文件
      name: 'setMessage',
      // 设置要传入云函数里的值
      data: {
        content: this.data.tempMsg,
        userInfo: this.data.userInfo,
        pic: this.data.tempPic
      }
    }).then(res => {
      // 弹框提示
      wx.showToast({
        title: '发表成功',
        icon: "none",
      })
      // 调用留言获取方法
      this.getMessage();
      // 清空临时数据
      this.setData({
        tempMsg: '',
        tempPic: '',
      })
    })
  },
  getMessage(e) {
    // 通过e回调判断页面是否触发翻页事件
    if (e) {
      if (e.currentTarget) {
        var val = e.currentTarget.dataset.val;
        // 更新current
        this.setData({
          current: this.data.current + val
        })
      }
    }
    // 获取数据库数据
    wx.cloud.callFunction({
      name: 'getMessage',
      data: {
        // 传入当前页数
        current: this.data.current || 1,
      }
    }).then(res => {
      console.log(res);
      var message = res.result.data;
      // 对message进行映射 格式化时间戳格式
      message.map(item => {
        item.date = formatTime(new Date(item.date));
        return item;
      })
      var pagination = res.result.pagination;
      this.setData({
        message,
        pagination
      })
    })
  },
  // 上传图片
  upImg() {
    var that = this;
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // 上传到服务器
        wx.cloud.uploadFile({
          cloudPath: 'my-photo-png',
          filePath: res.tempFilePaths[0],
          success: res => {
            that.setData({
              tempPic: res.fileID
            })
          }
        })
      }
    })
  },
  getUserProfile() {
    wx.getUserProfile({
      desc: '留言需要获取您的昵称',
      success: (res) => {
        console.log(res);
        // 获取成功,添加userInfo
        this.setData({
          userInfo: res.userInfo
        })
        // 存储在本地
        wx.setStorageSync('userInfo', res.userInfo)
        // 发送留言
        this.setMessage();
      },
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 默认从本地获取一次数据
    wx.getStorage({
      key: 'userInfo',
      success: (res) => {
        this.setData({
          userInfo: res.data
        })
      }
    })
    this.getMessage();
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})

home.wxss 样式

样式表

/* pages/home/home.wxss */
.msg{
  border-bottom: 1rpx solid #ccc;
  padding: 30rpx;
  display: flex;
}
.msg .date{
  font-size: 24rpx;
  color: #aaa;
}
.addArea{
  padding: 30rpx;
  padding-top: 0;
}
.addArea textarea{
  height: 200rpx;
  background-color: #f0f0f0;
  padding: 15rpx;
  margin-bottom: 30rpx;
  border-radius: 15rpx;
  box-sizing: border-box;
}
.addArea button{
  display: block;
}
.addArea .tempPic{
  width: 100rpx;
  height: 100rpx;
  margin: 10rpx;
}
.buttons{
  display: flex;
}
.buttons .btn{
  flex: 1;
  border-radius: 6px 0 0 6px;
}
.buttons .plus{
  margin: 0;
  padding: 0;
  width: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 0 6px 6px 0;
  background-color: #06AE57;
  color: #fff;
}
.avatar{
  margin-right: 30rpx;
}
.avatar image{
  width: 100rpx;
  height: 100rpx;
  border-radius: 100rpx;
}
.avatar text{
  font-size: 24rpx;
  color: #999;
  display: block;
  text-align: center;
}
.content{
  width: 100%;
  flex: 1;
}
.content image{
  width: 100%;
}
.pagination{
  display: flex;
  justify-content: flex-start;
  padding: 15rpx;
}
.pagination button{
  margin: 10rpx;
  padding: 10rpx;
  font-size: 24rpx !important;
}

utils.js工具文件

utils.js 工具文件

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  formatTime
}

完成

在这里插入图片描述

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值