1. 程式人生 > >第一章 “我要點爆”微信小程式雲開發之專案建立與我的頁面功能實現

第一章 “我要點爆”微信小程式雲開發之專案建立與我的頁面功能實現

第一章 “我要點爆”微信小程式雲開發之專案建立與我的頁面功能實現


開發環境搭建

使用自己的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