第一章 “我要點爆”微信小程序雲開發之項目建立與我的頁面功能實現
開發環境搭建
使用自己的AppID新建小程序項目,后端服務選擇小程序·雲開發,點擊新建,完成項目新建。
新建成功后跳轉到開發者工具界面
新建后,微信端為我們提供了一個參考的模板程序,這里我們自己來創建各個所需的文件與代碼,所以刪除所有不需要的文件,刪除cloudfunctions、miniprogram/images、miniprogram/pages文件下所有文件,同時也刪除style文件和刪除app.json中原始的頁面配置。
此時編譯下方控制台會報“VM8100:5 appJSON["pages"] 需至少存在一項”錯誤,因為app.json中未配置任何頁面路徑,下面我們來對app.json進行配置。
{
"cloud": true,
"pages": [
"pages/index/index",
"pages/detonation/detonation",
"pages/user/user"
],
“cloud”: true表示讓雲能力可以在所有基礎庫中使用,在頁面路徑列表pages下加入三個Tab頁面路徑,在window中設置全局的默認窗口樣式,通過tabBar設置底部tab欄的樣式,配置完成后點擊編譯,開發工具會自動生成三個頁面的文件夾以及相關文件。
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#FF3333",
"navigationBarTitleText": "我要點爆",
"navigationBarTextStyle": "white",
"backgroundColor": "#FF3333"
},
"tabBar": {
"backgroundColor": "#F2F2F2",
"color": "#6B6B6B",
"selectedColor": "#FF0000",
"list": [
{
"pagePath": "pages/index/index",
"text": "世界",
"iconPath": "/images/shi.png",
"selectedIconPath": "/images/shi1.png"
},
{
"pagePath": "pages/detonation/detonation",
"text": "點爆",
"iconPath": "/images/bao2.png",
"selectedIconPath": "/images/bao1.png"
},
{
"pagePath": "pages/user/user",
"text": "我的",
"iconPath": "/images/wo1.png",
"selectedIconPath": "/images/wo.png"
}
]
},
"sitemapLocation": "sitemap.json"
}
配置成功后頁面結構與效果
創建數據庫環境
設置環境名稱,環境名稱可以根據自己需求設置,這里設置與項目名相同dbx,下方的環境ID會自動生成,無需修改,點擊確定完成創建。
創建成功后跳轉雲開發控制台頁面
配置app.js文件,在調用雲開發各 API 前,需先調用初始化方法 init 一次(全局只需一次),在wx.cloud.init中設置程序所讀環境的數據庫位置,剛才創建的數據庫環境的ID
實現我的頁面布局制作與用戶授權登錄功能
首先對頁面進行布局,頭部使用一個button按鈕來進行授權登錄獲取用戶信息的操作,設置button的open-type為getUserInfo,使得按鈕可以從bindgetuserinfo回調中獲取到用戶信息,設置回調方法為getUserInfoHandler。為了讓用戶授權后實時更新用戶頭像與用戶名,這里使用數據綁定與判斷的方法。
<!-- pages/user/user.wxml --> <view class="user_header"> <view class="header_box"> <image src="{{userTx || defaultUrl}}"></image> <button class="{{username == '點擊登錄' ? 'usernameDe' : 'username'}}" open-type="getUserInfo" bindgetuserinfo="getUserInfoHandler">{{username}}</button> <view class="qiandao"> <text>糖果</text> </view> </view> </view> <view class="user_main"> <view class="main_box"> <view class="box_item"> <image src="/images/jilu.png"></image> <text>點爆記錄</text> </view> <view class="box_item"> <image src="/images/zhudian.png"></image> <text>最近助點</text> </view> </view> <view class="main_box"> <view class="box_item"> <image src="/images/fengcun.png"></image> <text>我的封存</text> </view> <view class="box_item"> <image src="/images/usercang.png"></image> <text>我的收藏</text> </view> </view> </view>
頁面布局完成后進行user.js的編寫,data中設置頁面初始數據,username用於控制授權按鈕用戶名變換,defaultUrl設置默認頭像,userTx記錄用戶頭像,userInfo記錄用戶授權后所獲取的信息,gender用與用戶性別判斷,province用於記錄地區信息。
// pages/user/user.js
Page({
data: {
username: '點擊登錄',
defaultUrl: '/images/yuyin5.png',
userTx: '',
userInfo: {},
gender: 1,
province: '',
},
在onLoad中對頁面進行初始化設置和用戶是否登錄的初始化設置,在用戶授權登錄后直接使用本地的用戶信息,如果本地信息不存在則通過wx.getSetting獲取用戶設置,看用戶是否授權過,如果授權過,則wx.getUserInfo直接獲取用戶信息。
onLoad: function () {
wx.setNavigationBarTitle({
title: '我的'
})
//當重新加載這個頁面時,查看是否有已經登錄的信息
let username = wx.getStorageSync('username'),
avater = wx.getStorageSync('avatar');
if (username) {
this.setData({
username: username,
userTx: avater
})
}
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
wx.getUserInfo({
success: res => {
this.setData({
userTx: res.userInfo.avatarUrl,
userInfo: res.userInfo
})
}
})
}
}
})
},
getUserInfoHandler方法保存系統常用的用戶信息到本地和完成用戶信息數據庫注冊,**button組件中bindgetuserinfo方法回調的detail數據與wx.getUserInfo返回的一致**,通過detail將所需的用戶信息提取出來,將性別gender替換為‘男’和‘女’,將頭像、用戶名、性別、地區保存在本地。然后使用雲數據庫API進行數據庫操作。
getUserInfoHandler: function (e) {
let d = e.detail.userInfo
var gen = d.gender == 1 ? '男' : '女'
this.setData({
userTx: d.avatarUrl,
username: d.nickName
})
wx.setStorageSync('avater', d.avatarUrl)
wx.setStorageSync('username', d.nickName)
wx.setStorageSync('gender', gen)
wx.setStorageSync('province', d.province)
//獲取數據庫引用
const db = wx.cloud.database()
const _ = db.command
//查看是否已有登錄,無,則獲取id
var userId = wx.getStorageSync('userId')
if (!userId) {
userId = this.getUserId()
}
//查找數據庫
db.collection('users').where({
_openid: d.openid
}).get({
success(res) {
// res.data 是包含以上定義的記錄的數組
//如果查詢到數據,將數據記錄,否則去數據庫注冊
if (res.data && res.data.length > 0) {
wx.setStorageSync('openId', res.data[0]._openid)
} else {
//定時器
setTimeout(() => {
//寫入數據庫
db.collection('users').add({
data: {
userId: userId,
userSweet: 10,
voice: 0,
baovoice: 0,
iv: d.iv
},
success: function () {
console.log('用戶id新增成功')
db.collection('users').where({
userId: userId
}).get({
success: res => {
wx.setStorageSync('openId', res.data[0]._openid)
},
fail: err => {
console.log('用戶_openId設置失敗')
}
})
},
fail: function (e) {
console.log('用戶id新增失敗')
}
})
}, 100)
}
},
fail: err => {
}
})
},
getUserId: function () {
//生產唯一id,采用一個字母或數字+1970年到現在的毫秒數+10w的一個隨機數組成
var w = "abcdefghijklmnopqrstuvwxyz0123456789",
firstW = w[parseInt(Math.random() * (w.length))];
var userId = firstW + (Date.now()) + (Math.random() * 100000).toFixed(0)
wx.setStorageSync('userId', userId)
return userId;
},
})
在雲開發控制台中創建數據庫集合,我們新建一個users集合,我們只需新建集合,通過js中使用雲開發API可自動創建集合中的屬性和數據。
該users集合為用戶信息表,記錄用戶信息,表users的結構如下:
集合創建成功后,點擊將出現進行編譯,此時頁面效果如下:
我們點擊“點擊登錄”按鈕,然后對程序進行授權,授權后可以看到我們的頭像和用戶名都顯示出來了,同時,打開雲開發控制台,查看users集合,可以看到我們信息已經成功保存在了集合中。
至此,我們就完成了
1、雲端控制台數據庫的創建
2、我的頁面的樣式制作
3、用戶授權登錄功能制作
4、雲數據庫的用戶數據存儲的實現
項目源碼:https://github.com/xiedong2016/dbx