小程序仿朋友圈、表白墙应用实现简单的发表功能

本人学习了小程序一个多月,刚开始时不知做些什么,就仿照微信朋友圈做了些内容,现在分享一下实现发表功能的代码,身为一个菜鸟,也请大佬们多指点!

先附上两张图片在这里插入图片描述

在这里插入图片描述
两张比较简洁的页面,发表的时候进入发表页面,输入内容,也可以附上一张图片,点击提交就可以正常发表了,发表后可以进到动态页面下拉刷新一下就可以查看,在这个过程中,都是用了小程序自带的云数据库(也是由于本人水平较低,后端那些技术还不怎么会),下面就上代码。

WXML 这也只是实现了一个简洁的页面,如果想变得更好看些,还可也在装饰一下。

<van-notice-bar mode="closeable" text="为了在主页面有更好的视觉体验,每次暂仅支持上传一张图片,敬请谅解!" />
<view class="page">
  <form bindsubmit="onSubmit">
    <view class="form">
      <view class="Inputwords">
        <view class="inputwords">
          <textarea class="text" placeholder="这一刻的想法" name="text" value="{{value}}" maxlength="-1" auto-height></textarea>
          <view class="AddImage">
            <block wx:for="{{FileID}}" wx:key="index">
              <image src="{{item}}" wx:if="{{FileID}}" class="addImages"></image>
            </block>
            <view class="addImages">
              <image src="/images/add2.png" class="inAddImages" catchtap="onImage"></image>
            </view>
          </view>
        </view>
      </view><view class="Meau">
      <view class="meau">
      <van-radio-group value="{{ radio }}" class="meau" bind:change="onChange">
        <van-radio class="van-radio" name="chat">闲聊</van-radio>
        <van-radio class="van-radio" name="express">表白</van-radio>
        <van-radio class="van-radio" name="save">卖舍友</van-radio>
        <van-radio class="van-radio" name="lost">失物招领</van-radio>
        <van-radio class="van-radio" name="help">帮忙</van-radio>
      </van-radio-group>
      </view>
      </view>
      <view class="Classroom"><text class="classroom">显示班级</text><view class="onclassroom"><switch name="classroom" /></view></view>
      <view class="Name"><text class="name">显示姓名</text><view class="onname"><switch name="realname" /></view></view>
      <van-cell icon="location" class="location" title="位置" is-link catchtap="onLocation" value="{{location}}" />
     <cover-view class="cover-view"> <button form-type="submit" class="submit" hover-class="button">提交</button></cover-view> 
    </view>
  </form>
</view>

注意:代码中使用了vant组件库,如果是直接复制代码的话应该先引入vant组件库。建议阅读这篇文章:关于微信小程序引入vant组件库的方法

WXSS 还是有一点混乱的,当时好像不是按顺序写的。

.page{
  margin: 0rpx;
  width: 750rpx;
  /* background-color: white; */
}
.Inputwords{
  width: 100%;
  background-color: white;
}
.inputwords{
  width: 710rpx;
  margin: 20rpx auto;
}
.Meau{
  width: 100%;
  margin-top:20rpx; 
  background-color: white;
}
.meau{
  width: 710rpx;
  margin: 0rpx auto;
}
.Classroom{
  width: 100%;
  height: 90rpx;
  background-color: white;
  margin-top:20rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content:space-between;
}
.classroom{
  margin-left:20rpx;  
}
.onclassroom{ 
  margin-right: 20rpx;
  display: flex;
  flex-direction: row;
  justify-content:flex-end;
}
.Name{
  width: 100%;
  height: 90rpx;
  background-color: white;
  border-top: 1px solid #e8e8e8;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content:space-between;
}
.name{
  margin-left:20rpx;
}
.onname{
  margin-right: 20rpx;
  display: flex;
  flex-direction: row;
  justify-content:flex-end;
}
.van-radio{
  margin-bottom: 10rpx;
}
.text{
  width: 100%;
  height: auto;
  color: black;
}
.AddImage{
  margin-top: 0rpx;
  display: flex;
  flex-direction: row;
}

.addImages{
  width: 200rpx;
  height: 200rpx;
  margin-top: 50rpx;
  border: 0.5px solid #bbb;
  background-color: #e8e8e8;
  float: left;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.inAddImages{
  width: 80rpx;
  height: 80rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.submit{
  width: 200rpx;
  color: white;
  background-color: blue;
  margin: 40rpx auto 20rpx auto;
}
.form{
  display: flex;
  flex-direction: column;
}
.radio-group{
  width: 100%;
  height: 80rpx;
  display: flex;
  align-items: center;
  margin-top: 30rpx;
}
.notname{
  width: 100%;
  height: 80rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  border-top: 1px solid #e8e8e8;
  border-bottom: 1px solid #e8e8e8;
  margin-top: 20rpx;
}
.onnotname{
  margin-left:40rpx;
  display: flex;
  flex-direction: row;
  justify-content:flex-end; 
}
.radio{
  margin-left: 20rpx;
}
.header {
    margin: 90rpx 0 90rpx 50rpx;
    border-bottom: 1px solid #ccc;
    text-align: center;
    width: 650rpx;
    height: 300rpx;
    line-height: 450rpx;
}
 
.bottom {
    border-radius: 80rpx;
    margin: 70rpx 50rpx;
    font-size: 35rpx;
}
.button{
    opacity: 0.9;
    background: #f7f7f7;
}
.meau{
  margin-top:30rpx; 
}
.location{
  width: 100%;
  margin-top: 20rpx;
}

.cover-view {
  position: absolute;
  bottom: calc(100rpx);
  width: 200rpx;
  margin-left: auto;
  margin-right: auto;
  left: calc(50% - 100rpx);
  /* opacity: .7; */
}

JS 由于JS代码比较多,这里就直接上传各部分的函数了

 // 选择图片
  onImage: function(e) {
    var that = this;
    //从相册选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        // const tempFilePaths = res.tempFilePaths;
        console.log(res.tempFilePaths[0])
        // let FileID=that.data.FileID;
        // for(let i=0;i<res.tempFilePaths.length;i++){
        //   FileID.push(res.tempFilePaths[i])
        // }
        that.setData({
          FileID: res.tempFilePaths //把fileID存入data 进而存入upload集合
        })
        console.log(that.data.FileID)
      }
    })
  },

其余的代码,这是点击提交时,将数据上传至云数据库。

注意:要看一下自己项目中的util.js文件在什么位置,下面的require中写相应的路由。

const db = wx.cloud.database();
var util = require('../../utils/utils.js');
Page({

  /*  *
   * 页面的初始数据
   */
  data: {
    value: '',
    radio: 'chat',
checked: true
  },
  onChange({ detail }) {
    // 需要手动对 checked 状态进行更新
    this.setData({ 
      checked: detail 
      });
  },
  onChange(event) {
    //   console.log(event)
    this.setData({
      radio: event.detail
    });
  },
  //选择位置
  onLocation: function(e) {
    var that = this
    wx.chooseLocation({
      success: function (res) {
        console.log(res)
        that.setData({
          location: res.name
        })
      }
    })
  },
  //提交按钮  上传数据
  onSubmit: function(e) {
    if (this.data.upload) {
      var that = this;
      console.log(that.data.location)
      var text = e.detail.value.text;
      // var menu = e.detail.value.menu;
      var menu = that.data.radio;
      var banji = e.detail.value.classroom;
      var realname = e.detail.value.realname
      console.log(e.detail.value)
      wx.showLoading({
        title: '正在上传',
        duration: 2000
      })
      //调用云函数,检测输入内容是否符合规定
      wx.cloud.callFunction({
        name: 'safeText',
        data: {
          text: text ? text : '1'
        },
        success: function(res) {
          //   console.log(res.result.errMsg)
          //如果符合规定,就进行上传
          if (res.result.errMsg == 'openapi.security.msgSecCheck:ok') {
            //获取用户openid 
            wx.cloud.callFunction({
              name: 'login',
              success: function(res) {
                var openid = res.result.openid;
                that.setData({
                  openid: openid
                })
                //如果有图片,就上传至云存储
                if (that.data.FileID) {
                  //   for (let i = 0; i < that.data.FileID.length;i++){
                  //将图片存入云端,并返回存储路径
                  wx.cloud.uploadFile({
                    cloudPath: new Date().getTime() + '.png', //存入云端路径
                    filePath: that.data.FileID[0], //临时路径
                    success: function(res) {
                      console.log(res.fileID);
                      that.setData({
                        fileID: res.fileID, //把fileID存入data 进而存入upload集合
                      })
                      //在数据库查找该openid
                      db.collection('users').where({
                        _openid: openid
                      }).get({
                        success: function(res) { //成功通过openID获取用户昵称后   将信息存入数据库                  
                          that.setData({
                            interName: res.data[0].interName,
                            headImage: res.data[0].headImage,
                            realname: res.data[0].name ? res.data[0].name:false,
                            banji: res.data[0].banji?res.data[0].banji:false
                          })
                          //将用户输入的内容及用户信息写入数据库
                          db.collection('upload').add({
                            data: {
                              name: that.data.interName,
                              text: text,
                              count: 0,
                              eyeNum: 0,
                              menu: menu,
                              headImage: that.data.headImage,
                              fileID: that.data.fileID,
                              time: util.formatTime(new Date()),
                              location: that.data.location ? that.data.location:false,
                              realname:realname?that.data.realname:false,
                              banji: banji ? that.data.banji:false,
                              comment:[],
                              createTime: db.serverDate() //发表时间,用来获取数据库信息用
                            },
                            //成功后去掉现实的图片
                            success: function(res) {
                              // console.log(that.data.interName);
                              // console.log(util.formatTime(new Date()));
                              that.setData({
                                FileID: false,
                                fileID: false
                              })
                              //弹窗提示发表成功
                              wx.showToast({
                                title: '发表成功!',
                                icon: 'success',
                                image: '',
                                duration: 1000,
                                mask: true,
                                success: function(res) {},
                                fail: function(res) {},
                                complete: function(res) {},
                              })
                              that.setData({
                                value: ''
                              })
                            }
                          })
                        },
                        fail: function(err) {
                          console.log(err)
                        }
                      })
                    },
                    fail: function(err) {
                      console.log(err)
                    }
                  })
                }
                // 用户没有选择图片,则不上传图片
                else {
                  //在数据库查找该openid
                  db.collection('users').where({
                    _openid: openid
                  }).get({
                    success: function(res) { //成功通过openID获取用户昵称后   将信息存入数据库                  
                      that.setData({
                        interName: res.data[0].interName,
                        headImage: res.data[0].headImage,
                        realname: res.data[0].name ? res.data[0].name : false,
                        banji: res.data[0].banji ? res.data[0].banji : false
                      })
                      //将用户输入的内容及用户信息写入数据库
                      db.collection('upload').add({
                        data: {
                          name: that.data.interName, //判断是否是匿名,若是匿名名字变成‘匿名’
                          text: text,
                          count: 0,
                          eyeNum: 0,
                          menu: menu,
                          headImage: that.data.headImage,
                          fileID: false,
                          time: util.formatTime(new Date()),
                          location: that.data.location ? that.data.location : false,
                          realname: realname ? that.data.realname : false,
                          banji: banji ? that.data.banji : false,
                          comment: [],
                          createTime: db.serverDate() //发表时间,用来获取数据库信息用
                        },
                        //成功后去掉现实的图片
                        success: function(res) {
                          // console.log(that.data.interName);
                          // console.log(util.formatTime(new Date()));
                          that.setData({
                            FileID: false,
                            fileID: false
                          })
                          //弹窗提示发表成功
                          wx.showToast({
                            title: '发表成功!',
                            icon: 'success',
                            image: '',
                            duration: 1000,
                          })
                          that.setData({
                            value: ''
                          })
                        }
                      })
                    },
                    fail: function(err) {
                      console.log(err)
                    }
                  })
                }
              }
            })
          }
          //如果存在敏感词汇,则无法上传
          else {
            wx.showModal({
              title: '警告',
              content: '您发布的内容不符合规定,请重新输入!',
            })
          }
        },
        fail: function(err) {
          console.log(err)
        }
      })
    } else {
      wx.showModal({
        title: '警告',
        content: '请先登陆在进行发表!',
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //检查数据库是否有该用户信息,若没有则进行获取并存储
    var that = this;
    //通过云函数获取openid
    wx.cloud.callFunction({
      name: 'login',
      success: function(res) {
        //  console.log(res.result.openid)
        var openid = res.result.openid;
        db.collection('users').where({
          _openid: openid
        }).get({
          success: function(e) {
            if (e.data.length) {
              that.setData({
                user: e.data[0],
                upload: true
              })
            } else {
              wx.showModal({
                title: '提示',
                content: '您当前处于未登录状态,请先到“我的”界面完成登录,否则将无法发表内容',
              })
              that.setData({
                upload: false
              })
            }
          },
          fail: function(e) {
          }
        })
      },
      fail: function (err) {    
        console.log(err)
      }
    })
  }
  })

注意:为了能让大家更方便,我把上传这一部分的代码全部放上了,但在使用的时候一定要注意我的代码中都有什么集合,也需要在你的云数据库中建立同名的集合才能够保证想要发表的内容正常存储到云数据库中的,否则将不能正常上传。

点击提交后,数据就会存入云数据库了,之后显示的时候通过读取数据库的内容再显示出来就可以,关于读取数据库的内容和显示以及实现点赞和分享的功能会在下一篇内容写出。
基本的代码就是这些了,大部分内容都注释了一下,都是些本人的拙见,如果有什么问题或建议,欢迎在下方评论留言。

  • 7
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 16
    评论
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旁观者lgp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值