实现的功能是用户上传自己的资料,给大家看。其实就是一个交友、婚恋、相亲的免费广告平台。
先看效果
,此外增加了按性别和年龄筛选
主要代码:
01列表页
<!--index.wxml-->
<label bindtap="toExample">案例</label>
<!-- <form bindsubmit="formSubmit">
<select></select>
<input name="name" placeholder="请输入名字"></input>
<button form-type="submit">submit</button>
</form> -->
<view class="section">
<picker bindchange="bindPickerChange" value="{{index}}" range="{{array}}">
<view class="picker">
性别:{{array[index]}}
</view>
</picker>
<picker mode="multiSelector" bindchange="bindMultiPickerChange" value="{{multiIndex}}" range="{{multiArray}}">
<view class="picker">
年龄:{{multiArray[0][multiIndex[0]]}}~{{multiArray[1][multiIndex[1]]}}
</view>
</picker>
</view>
<image class="add" src="../../images/icon-add.png" bindtap="add"/>
<view class="container" wx:for="{{queryResult}}" wx:key="_id">
<view class="card">
<image class="touxiang" src="{{item.imgUrl}}"
data-imgurl="{{item.imgUrl}}"
bindtap="previewImg"/>
<view class="biaoqian">
<label>{{item.nickname}}</label>
<label>{{item.sex===0?'男♂':'女♀'}}
</label>
<label>{{item.age}}岁</label>
<label>{{item.income}}k</label>
<label>{{item.occupation}}</label>
<label>{{item.eduLevel}}</label>
<label>{{item.height}}cm</label>
<label>{{item.weight}}kg</label>
<label>家乡:{{item.hometown}}</label>
<label>现居:{{item.liveIn}}</label>
</view>
<view style="margin:0 5px; font-size:smalle">联系方式:{{item.contactWay}}</view>
</view>
</view>
.touxiang{
margin: 5px 5px 0 5px;
width:25%;
height: 85px;
}
.biaoqian{
position: relative;
display: inline-block;
width:70%;
}
.card{
border:solid 1px rgb(255, 2, 2);
width:90%;
border-radius: 10px;
margin-top: 15px;
padding: 5px;
background-color: white;
}
.card label{
display: inline-block;
margin-right: 18px;
margin-bottom: 2px;
font-size: smaller;
color: cornflowerblue;
padding: 1.5px;
border-radius: 5px;
border: 1px solid grey;
}
.add{
position: fixed;
width:60px;
height: 60px;
top: 560px;
right: 20px;
z-index: 2;
}
.picker{
float: left;
margin-left: 20%;
}
//index.js
const app = getApp()
Page({
data: {
queryResult:[],
array: ['男','女'],
index: 0,
multiArray: [[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35], [18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35]],
multiIndex: [0, 0],
queryParam:{}
},
onLoad: function() {
if (!wx.cloud) {
wx.redirectTo({
url: '../chooseLib/chooseLib',
})
return
}
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true,
})
}
const db = wx.cloud.database()
// 查询当前用户所有的 counters,默认查男生
db.collection('mkf_users').where({sex: 0}).get({
success: res => {
this.setData({
queryResult: res.data
})
console.log(this.data.queryResult);
console.log('[数据库] [查询记录] 成功: ', res)
},
fail: err => {
wx.showToast({
icon: 'none',
title: '查询记录失败'
})
console.error('[数据库] [查询记录] 失败:', err)
}
})
console.log(this.data.queryResult);
},
getUserProfile() {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
this.setData({
avatarUrl: res.userInfo.avatarUrl,
userInfo: res.userInfo,
hasUserInfo: true,
})
}
})
},
onGetUserInfo: function(e) {
if (!this.data.logged && e.detail.userInfo) {
this.setData({
logged: true,
avatarUrl: e.detail.userInfo.avatarUrl,
userInfo: e.detail.userInfo,
hasUserInfo: true,
})
}
},
onGetOpenid: function() {
// 调用云函数
console.log('获取openid')
wx.cloud.callFunction({
name: 'login',
data: {},
success: res => {
console.log('[云函数] [login] user openid: ', res.result.openid)
app.globalData.openid = res.result.openid
wx.setStorageSync('openid', res.result.openid);
// wx.navigateTo({
// url: '../userConsole/userConsole',
// })
},
fail: err => {
console.error('[云函数] [login] 调用失败', err)
wx.navigateTo({
url: '../deployFunctions/deployFunctions',
})
}
})
},
// 上传图片
doUpload: function () {
// 选择图片
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
wx.showLoading({
title: '上传中',
})
const filePath = res.tempFilePaths[0]
// 上传图片
const cloudPath = `my-image${filePath.match(/\.[^.]+?$/)[0]}`
wx.cloud.uploadFile({
cloudPath,
filePath,
success: res => {
console.log('[上传文件] 成功:', res)
app.globalData.fileID = res.fileID
app.globalData.cloudPath = cloudPath
app.globalData.imagePath = filePath
wx.navigateTo({
url: '../storageConsole/storageConsole'
})
},
fail: e => {
console.error('[上传文件] 失败:', e)
wx.showToast({
icon: 'none',
title: '上传失败',
})
},
complete: () => {
wx.hideLoading()
}
})
},
fail: e => {
console.error(e)
}
})
},
formSubmit(e) {
console.log('form发生了submit事件,携带数据为:', e.detail.value)
},
add(){
console.log('add one');
this.onGetOpenid();
const openid = wx.getStorageSync('openid');
console.log(openid);
wx.navigateTo({
url: '../page01/index',
})
},
toExample(){
wx.navigateTo({
url: '../example/index',
})
},
bindPickerChange: function(e) {
console.log('picker发送选择改变,携带值为', e.detail.value)
this.setData({
index: e.detail.value,
queryParam:{...this.data.queryParam,sex:Number(e.detail.value)}
})
console.log(this.data.queryParam);
const queryParam = this.data.queryParam;
const db = wx.cloud.database()
let q = db.collection('mkf_users');
if(queryParam.age1){
q = q.where({age:{'$gte' : queryParam.age1, '$lte' : queryParam.age2}}).where({sex: queryParam.sex});
}else{
q = q.where({sex: queryParam.sex});
}
q.get({
success: res => {
this.setData({
queryResult: res.data
})
console.log('[数据库] [查询记录] 成功: ', res)
},
fail: err => {
wx.showToast({
icon: 'none',
title: '查询记录失败'
})
console.error('[数据库] [查询记录] 失败:', err)
}
})
},
bindMultiPickerChange: function (e) {
console.log('picker发送选择改变,携带值为', e.detail.value);
const s=e.detail.value;
const age1 = this.data.multiArray[0][s[0]];
const age2 = this.data.multiArray[1][s[1]];
this.setData({
multiIndex: e.detail.value,
queryParam:{...this.data.queryParam,age1:age1,age2:age2}
})
console.log(this.data.queryParam);
const queryParam = this.data.queryParam;
const db = wx.cloud.database()
let q = db.collection('mkf_users');
if(queryParam.sex){
q = q.where({age:{'$gte' : queryParam.age1, '$lte' : queryParam.age2}}).where({sex: queryParam.sex});
}else{
q = q.where({age:{'$gte' : queryParam.age1, '$lte' : queryParam.age2}}).where({sex: 0});
}
q.get({
success: res => {
this.setData({
queryResult: res.data
})
console.log('[数据库] [查询记录] 成功: ', res)
},
fail: err => {
wx.showToast({
icon: 'none',
title: '查询记录失败'
})
console.error('[数据库] [查询记录] 失败:', err)
}
})
},
//图片预览
previewImg(e){
console.log(e);
wx.previewImage({
urls: [e.target.dataset.imgurl],
})
},
})
02 上传资料页
<!--index.wxml-->
<view class="container">
添加资料
<view class="page-body">
<form catchsubmit="formSubmit" catchreset="formReset">
<view class="page-section page-section-gap">
<radio-group name="sex">
<label><radio value="0"/>男♂</label>
<label><radio value="1"/>女♀</label>
</radio-group>
</view>
<view class="page-section">
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__bd" style="margin: 30rpx 0" >
<input type="text" class="weui-input" name="nickname" placeholder="昵称" />
<input type="number" class="weui-input" name="age" placeholder="年龄" />
<input type="number" class="weui-input" name="height" placeholder="身高 单位(cm)" />
<input type="number" class="weui-input" name="weight" placeholder="体重 单位(kg)" />
<input type="number" class="weui-input" name="income" placeholder="收入 单位(k)" />
<input class="weui-input" name="eduLevel" placeholder="学历" />
<input class="weui-input" name="occupation" placeholder="职业" />
<input class="weui-input" name="liveIn" placeholder="现居" />
<input class="weui-input" name="hometown" placeholder="家乡" />
<input class="weui-input" name="contactWay" placeholder="联系方式" />
<view class="uploader">
<view class="uploader-text" bindtap="doUpload">
<text>上传照片</text>
</view>
<view class="uploader-container" wx:if="{{imgUrl}}">
<image class="uploader-image" src="{{imgUrl}}" mode="aspectFit"
data-imgurl="{{imgUrl}}"
bindtap="previewImg"></image>
</view>
</view>
</view>
</view>
</view>
</view>
<view class="btn-area">
<button style="margin: 30rpx 0" type="primary" formType="submit">Submit</button>
<button style="margin: 30rpx 0" formType="reset">Reset</button>
</view>
</form>
</view>
</view>
const app = getApp()
Page({
data: {
fileID: '',
cloudPath: '',
imgUrl: '',
},
onLoad: function (options) {
if (app.globalData.openid) {
this.setData({
openid: app.globalData.openid
})
}
},
onAdd: function (user) {
const db = wx.cloud.database()
db.collection('mkf_users').add({
data: {
age: user.age,
occupation: user.occupation,
nickname: user.nickname,
hometown: user.hometown,
eduLevel: user.eduLevel,
income: user.income,
liveIn: user.liveIn,
contactWay: user.contactWay,
weight: user.weight,
height: user.height,
imgUrl: user.imgUrl,
sex: user.sex,
},
success: res => {
// 在返回结果中会包含新创建的记录的 _id
this.setData({
counterId: res._id,
count: 1
})
wx.showToast({
title: '新增记录成功',
})
console.log('[数据库] [新增记录] 成功,记录 _id: ', res._id)
},
fail: err => {
wx.showToast({
icon: 'none',
title: '新增记录失败'
})
console.error('[数据库] [新增记录] 失败:', err)
}
})
},
formSubmit(e) {
console.log('form发生了submit事件,携带数据为:', e.detail.value);
const user = e.detail.value;
if(user.nickname===""){
wx.showToast({
icon:'error',
title: '昵称必填!',
})
return;
}
if(user.contactWay===""){
wx.showToast({
icon:'error',
title: '联系方式必填!',
})
return;
}
if(user.eduLevel===""){
wx.showToast({
icon:'error',
title: '学历必填!',
})
return;
}
if(user.height===""){
wx.showToast({
icon:'error',
title: '身高必填!',
})
return;
}
if(user.hometown===""){
wx.showToast({
icon:'error',
title: '家乡必填!',
})
return;
}
if(user.income===""){
wx.showToast({
icon:'error',
title: '收入必填!',
})
return;
}
if(user.liveIn===""){
wx.showToast({
icon:'error',
title: '现居地必填!',
})
return;
}
if(user.occupation===""){
wx.showToast({
icon:'error',
title: '职业必填!',
})
return ;
}
if(user.weight===""){
wx.showToast({
icon:'error',
title: '体重必填!',
})
return ;
}
if(user.sex===""){
wx.showToast({
icon:'error',
title: '性别必填!',
})
return;
}
user['imgUrl']=this.data.imgUrl;
if(user.imgUrl===''){
wx.showToast({
icon:'error',
title: '请上传照片!',
})
return ;
}
this.onAdd(user);
},
// 上传图片
doUpload: function () {
let _this = this;
// 选择图片
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
wx.showLoading({
title: '上传中',
})
const filePath = res.tempFilePaths[0]
// 上传图片
const suffix = `${filePath.match(/\.[^.]+?$/)[0]}`
const cloudPath = app.globalData.openid +suffix;
wx.cloud.uploadFile({
cloudPath,
filePath,
success: res => {
console.log('[上传文件] 成功:', res)
if(res.fileID){
_this.setData({imgUrl:res.fileID})
}
app.globalData.fileID = res.fileID
app.globalData.cloudPath = cloudPath
app.globalData.imagePath = filePath
// wx.navigateTo({
// url: '../storageConsole/storageConsole'
// })
},
fail: e => {
console.error('[上传文件] 失败:', e)
wx.showToast({
icon: 'none',
title: '上传失败',
})
},
complete: () => {
wx.hideLoading()
}
})
},
fail: e => {
console.error(e)
}
})
},
previewImg(e){
console.log(e);
wx.previewImage({
urls: [e.target.dataset.imgurl],
})
},
formReset(e) {
console.log('form发生了reset事件,携带数据为:', e.detail.value)
this.setData({
chosen: ''
})
}
})
总结:
微信小程序推出的这个云开发真的好用,极大简化了数据库等资源的配置,开发部署也相当简单。