微信小程序 宠物论坛1
微信小程序宠物论坛1
一个简单的论坛包括以下几个方面:
- 登录模块
- 发帖模块
- 首页模块
- 帖子详情模块
- 搜索模块
- 个人主页模块
下面将从这6个方面介绍如何用微信小程序开发一个简单的论坛。
登录模块
先看界面图
打开小程序首先看到这个界面,之后我们点击头像便完成授权登录。
JS部分
//index.js
//获取应用实例
const app = getApp()
const db = wx.cloud.database()Page({data: {motto: '欢迎来到宠物论坛',userInfo: {},nickname:"",heads:"",hasUserInfo: false,canIUse: wx.canIUse('button.open-type.getUserInfo')},onLoad: function () {if (app.globalData.userInfo) {this.setData({userInfo: app.globalData.userInfo,hasUserInfo: true})} else if (this.data.canIUse) {// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回// 所以此处加入 callback 以防止这种情况app.userInfoReadyCallback = res => {this.setData({userInfo: res.userInfo,heads:res.userInfo.avatarUrl,nickname:res.userInfo.nickName,hasUserInfo: true})// console.log(this.data.heads)// console.log(this.data.nickname)}} else {// 在没有 open-type=getUserInfo 版本的兼容处理wx.getUserInfo({success: res => {app.globalData.userInfo = res.userInfothis.setData({userInfo: res.userInfo,heads: res.userInfo.avatarUrl,hasUserInfo: true})}})}// 获取用户openidwx.cloud.callFunction({name: "getopenid",success: res => {console.log(res.result.openid)// this.setData({// openid: res.result.openid// })console.log(res.result.openid)this.setData({openid1: res.result.openid})console.log("openid1的值为:"+this.data.openid1)},fail(res) {console.log("获取openid失败")}})// 获取用户的openid,然后对比数据库,如果是老用户直接跳转const db = wx.cloud.database();db.collection('user').where({_openid: this.data.openid1}).get({success: function (res) {console.log("查询成功")console.log(res.data)if(res.data!=''){wx.reLaunch({url: '../mine/mine?id=openid1'})}console.log("openid2的值为:"+res.data[0]._openid)this.setData({openid2:res.data[0]._openid})}})// if (this.data.openid1 == this.data.openid2) (// wx.reLaunch({// url: '../mine/mine?id=openid1'// })// )},getUserInfo: function (e) {console.log(e)app.globalData.userInfo = e.detail.userInfothis.setData({userInfo: e.detail.userInfo,heads: e.userInfo.avatarUrl,hasUserInfo: true})},//如果是新用户 点击头像处理函数bindViewTap: function () {const heads=this.data.headsconst nickname=this.data.nicknamedb.collection('user').add({data: {nickname:nickname,heads:heads},success: function (res) {this.setData({openid:res._openid})}})const openid=this.data.openidwx.reLaunch({url: '../mine/mine?id=openid'})},})
WXML部分
<view class="container"><view class="userinfo"><button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button><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 class="usermotto"><text class="user-motto">{{motto}}</text></view>
</view>
WXSS部分
/**index.wxss**/
.userinfo {display: flex;flex-direction: column;align-items: center;
}.userinfo-avatar {width: 128rpx;height: 128rpx;margin: 20rpx;border-radius: 50%;
}.userinfo-nickname {color: #aaa;
}.usermotto {margin-top: 200px;
}