雲開發實戰分享|一天搭建一個社區

原創:龍衣css

前言

雖然不會後臺開發,可是也想本身作項目,正好雲開發出現了。開發者可使用雲開發開發微信小程序、小遊戲,無需搭建服務器,便可使用雲端能力。 社區做爲一個交流的平臺,能夠經過發佈本身、別人喜歡的文字、圖片的方式進行交流分享。 剛學完雲開發,正好能夠用社區小程序項目練練手~數據庫

【社區小程序】功能實現

首頁【廣場】小程序

●顯示用戶發佈的內容
●管理員發佈的一些教程
複製代碼

消息【發佈】微信小程序

●發佈圖文
●水平圖片的滑動顯示
複製代碼

我的中心【個人】數組

●顯示用戶的登陸信息
●用戶的收藏列表
●發佈歷史
●邀請好友
●產品意見
複製代碼

1、首頁【廣場】

  • 顯示用戶發佈的內容
  • 管理員發佈的一些教程

實現的效果

實現要點

1.WXML 不一樣類別數據的顯示

經過 if-elif-else 實現,在 wxml文件中經過 <block></block>渲染,由於它僅僅是一個包裝元素,不會在頁面中作任何渲染,只接受控制屬性。也就是說能夠經過屬性來控制頁面是否要渲染這部分的內容,能夠減小頁面渲染時間。bash

2.雲開發數據的獲取

先開通雲開發功能 ,參考官方文檔,而後在建立項目的時候勾選上 使用雲開發模板(看我的吧,我直接使用後點擊項目中的 login)就能夠獲取到用戶的 oppenid,以後就可使用雲數據庫了。服務器

  • 雲開發登陸:

  • 雲數據的獲取:
/**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function(options) {
    console.log('onload');
    this.getData(this.data.page);    
  },
  /**
   * 獲取列表數據
   * 
   */
  getData: function(page) {
    var that = this;
    console.log("page--->" + page);
    const db = wx.cloud.database();
    // 獲取總數
    db.collection('topic').count({
      success: function(res) {
        that.data.totalCount = res.total;
      }
    })
    // 獲取前十條
    try {
      db.collection('topic')
        .where({
          _openid: 'oSly***********vU1KwZE', // 填入當前用戶 openid
        })
        .limit(that.data.pageSize) // 限制返回數量爲 10 條
        .orderBy('date', 'desc')
        .get({
          success: function(res) {
            // res.data 是包含以上定義的兩條記錄的數組
            // console.log(res.data)
            that.data.topics = res.data;
            that.setData({
              topics: that.data.topics,
            })
            wx.hideNavigationBarLoading();//隱藏加載
            wx.stopPullDownRefresh();
            
          },
          fail: function(event) {
            wx.hideNavigationBarLoading();//隱藏加載
            wx.stopPullDownRefresh();
          }
        })
    } catch (e) {
      wx.hideNavigationBarLoading();//隱藏加載
      wx.stopPullDownRefresh();
      console.error(e);
    }
  },
複製代碼
  • 雲數據的添加:
/**
   * 保存到發佈集合中
   */
  saveDataToServer: function(event) {
    var that = this;
    const db = wx.cloud.database();
    const topic = db.collection('topic')
    db.collection('topic').add({
      // data 字段表示需新增的 JSON 數據
      data: {
        content: that.data.content,
        date: new Date(),
        images: that.data.images,
        user: that.data.user,
        isLike: that.data.isLike,
      },
      success: function(res) {
        // res 是一個對象,其中有 _id 字段標記剛建立的記錄的 id
        // 清空,而後重定向到首頁
        console.log("success---->" + res)
        // 保存到發佈歷史
        that.saveToHistoryServer();
        // 清空數據
        that.data.content = "";
        that.data.images = [];

        that.setData({
          textContent: '',
          images: [],
        })

        that.showTipAndSwitchTab();

      },
      complete: function(res) {
        console.log("complete---->" + res)
      }
    })
  },
複製代碼

3.數據列表的分頁

主要就是定義一個臨時數組存放加載上來的數據,而後經過傳遞給對象,最後傳遞到佈局中去。微信

/**
   * 頁面上拉觸底事件的處理函數
   */
  onReachBottom: function() {
    var that = this;
    var temp = [];
    // 獲取後面十條
    if(this.data.topics.length < this.data.totalCount){
      try {
        const db = wx.cloud.database();
        db.collection('topic')
          .skip(5)
          .limit(that.data.pageSize) // 限制返回數量爲 5 條
          .orderBy('date', 'desc')	// 排序
          .get({
            success: function (res) {
              // res.data 是包含以上定義的兩條記錄的數組
              if (res.data.length > 0) {
                for(var i=0; i < res.data.length; i++){
                  var tempTopic = res.data[i];
                  console.log(tempTopic);
                  temp.push(tempTopic);
                }

                var totalTopic = {};
                totalTopic =  that.data.topics.concat(temp);

                console.log(totalTopic);
                that.setData({
                  topics: totalTopic,
                })
              } else {
                wx.showToast({
                  title: '沒有更多數據了',
                })
              }


            },
            fail: function (event) {
              console.log("======" + event);
            }
          })
      } catch (e) {
        console.error(e);
      }
    }else{
      wx.showToast({
        title: '沒有更多數據了',
      })
    }
    
  },
複製代碼

2、消息【發佈】

  • 發佈圖文
  • 水平圖片的滑動顯示(效果不是很好,能夠改成九宮格實現)

發佈頁面效果以下:

分析如何實現

  • 導航欄的實現很簡單就不說了,可參考我以前的文章
  • 重點是中間的 ② 是內容區域
  • 區域三是功能操做區

內容區域的實現

  • 第一個是文本區域
  • 第二個是水平的圖片展現區域

在圖片的右上角有關閉按鈕,這裏使用的是 icon組件。ide

主要的實現代碼以下:函數

<view class="content">
  <form bindsubmit="formSubmit">
    <view class="text-content">
      <view class='text-area'>
        <textarea name="input-content" type="text" placeholder="說點什麼吧~" placeholder-class="holder" value="{{textContent}}" bindblur='getTextAreaContent'></textarea>
      </view>

    </view>
    <scroll-view class="image-group" scroll-x="true">
      <block wx:for='{{images}}' wx:for-index='idx'>
      <view>
        <image src='{{images[idx]}}' mode='aspectFill' bindtap="previewImg"></image>
        <icon type='clear' bindtap='removeImg'  data-index="{{idx}}" ></icon>
      </view>
      </block>
      
    </scroll-view>
    <view class='btn-func'>
      <button class="btn-img" bindtap='chooseImage'>選擇圖片</button>
      <button class="btn" formType='submit'  open-type="getUserInfo">發佈圈圈</button>
      <!-- <image hidden=''></image> -->
    </view>
  </form>

</view>
複製代碼

佈局樣式以下:

.content {
  height: 100%;
  width: 100%;
}

textarea {
  width: 700rpx;
  padding: 25rpx 0;
}

.text-content {
  background-color: #f3efef;
  padding: 0 25rpx;
}

.image-group {
  display: flex;
  white-space: nowrap;
  margin-top: 30px;
}

.image-group view{
  display: inline-block;
  flex-direction: row;
  width: 375rpx;
  height: 375rpx;
  margin-right: 20rpx;
  margin-left: 20rpx;
  background-color: #cfcccc;
}

.image-group view image{
  width: 100%;
  height: 100%;
  align-items: center;
}

.image-group view icon{
  display: inline-block;
  vertical-align: top;
  position: absolute
}
.btn-func {
  display: flex;
  flex-direction: column;
  width: 100%;
  position: absolute;
  bottom: 0;
  margin: 0 auto;
  align-items: center;
}

.btn-img {
  width: 220px;
  height: 45px;
  line-height: 45px;
  margin-top: 20px;
  margin-bottom: 20px;
  background-color: rgb(113, 98, 250);
  color: #fff;
  border-radius: 50px;
}

.btn {
  width: 220px;
  height: 45px;
  line-height: 45px;
  background-color: #d50310;
  color: #fff;
  border-radius: 50px;
  margin-bottom: 20px;
}
複製代碼

頁面佈局以後就該從 js中去處理數據了,在 js中主要實現的功能有:

  • 文本內容的獲取
  • 圖片的選擇
  • 圖片的閱覽
  • 圖片的刪除
  • 將結果發佈到雲數據庫中

1.文本內容的獲取

/**
   * 獲取填寫的內容
   */
  getTextAreaContent: function(event) {
    this.data.content = event.detail.value;
  },
複製代碼

2.圖片的選擇

/**
   * 選擇圖片
   */
  chooseImage: function(event) {
    var that = this;
    wx.chooseImage({
      count: 6,
      success: function(res) {
        // tempFilePath能夠做爲img標籤的src屬性顯示圖片
        const tempFilePaths = res.tempFilePaths

        for (var i in tempFilePaths) {
          that.data.images = that.data.images.concat(tempFilePaths[i])
        }
        // 設置圖片
        that.setData({
          images: that.data.images,
        })
      },
    })
  },
複製代碼

3.圖片的預覽

// 預覽圖片
  previewImg: function(e) {
    //獲取當前圖片的下標
    var index = e.currentTarget.dataset.index;

    wx.previewImage({
      //當前顯示圖片
      current: this.data.images[index],
      //全部圖片
      urls: this.data.images
    })
  },
複製代碼

4.圖片的刪除

/**
   * 刪除圖片
   */
  removeImg: function(event) {
    var position = event.currentTarget.dataset.index;
    this.data.images.splice(position, 1);
    // 渲染圖片
    this.setData({
      images: this.data.images,
    })
  },
複製代碼

5.發佈內容到數據庫中

數據發佈到數據中,須要先開啓雲開發,而後在數據庫中建立集合也就是表以後就是調用數據庫的增刪改查API便可。

/**
   * 添加到發佈集合中
   */
  saveToHistoryServer: function(event) {
    var that = this;
    const db = wx.cloud.database();
    db.collection('history').add({
      // data 字段表示需新增的 JSON 數據
      data: {
        content: that.data.content,
        date: new Date(),
        images: that.data.images,
        user: that.data.user,
        isLike: that.data.isLike,
      },
      success: function(res) {
        // res 是一個對象,其中有 _id 字段標記剛建立的記錄的 id
        console.log(res)
      },
      fail: console.error
    })
  },
複製代碼

3、我的中心【個人】

  • 【顯示用戶的登陸信息】主要就是調用小程序接口,獲取用戶的微信公開信息進行展現
  • 【用戶的收藏列表】獲取數據庫中的收藏列表進行展現
  • 【發佈歷史】在發佈頁面,當發佈成功將數據存到發佈歷史表中,須要的時候獲取該表的數據進行展現
  • 【邀請好友】調用小程序的分享接口,直接分享給微信羣,或者我的
  • 【產品意見】一個相似於發佈頁的頁面,實現思路和發佈頁實現是同樣的。

實現的效果

實現分析

1.要實現的效果

  • 在用戶進入我的中心,直接彈出獲取用戶信息彈窗
  • 顯示圓形的用戶頭像

2.受權彈窗

官方獲取用戶信息文檔調整

爲優化用戶體驗,使用 wx.getUserInfo 接口直接彈出受權框的開發方式將逐步再也不支持。從2018年4月30日開始,小程序與小遊戲的體驗版、開發版調用 wx.getUserInfo 接口,將沒法彈出受權詢問框,默認調用失敗。正式版暫不受影響。

也就是之前的 wx.getUserInfo不直接彈出受權窗口了,並且在新版中調用會直接返回fail,如今的作法呢就是經過點擊一個button 去實現用戶受權功能。

文檔中說明了有兩種方式可以獲取用戶信息。

  • 一個是利用 <open-data>獲取公開的用戶信息:
<open-data type="userNickName" lang="zh_CN"></open-data>
<open-data type="userAvatarUrl"></open-data>
<open-data type="userGender" lang="zh_CN"></open-data>
複製代碼
  • 另外一個是利用button 組件將 open-type 指定爲 getUserInfo類型:
<!-- 須要使用 button 來受權登陸 -->
  <button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">受權登陸</button>
  <view wx:else>請升級微信版本</view>

Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function() {
    // 查看是否受權
    wx.getSetting({
      success (res){
        if (res.authSetting['scope.userInfo']) {
          // 已經受權,能夠直接調用 getUserInfo 獲取頭像暱稱
          wx.getUserInfo({
            success: function(res) {
              console.log(res.userInfo)
            }
          })
        }
      }
    })
  },
  bindGetUserInfo (e) {
  // 獲取到用戶信息
    console.log(e.detail.userInfo)
  }
})
複製代碼

3.中實現圓形頭像

<view class='amountBg'>
  <view class='img'>
    <open-data type="userAvatarUrl"></open-data>
  </view>
  <view class='account'>
    <view class='nick-name'>
      <open-data type="userNickName" lang="zh_CN"></open-data>
    </view>
    <view class='address'>
      <open-data type="userCountry" lang="zh_CN"></open-data>·
      <open-data type="userProvince" lang="zh_CN"></open-data>·
      <open-data type="userCity" lang="zh_CN"></open-data>
    </view>
  </view>
</view>
複製代碼

css 樣式以下:

.amountBg {
  display: flex;
  flex-direction: row;
  height: 100px;
  background-color: #5495e6;
  align-items: center;
}

.img {
  overflow: hidden;
  display: block;
  margin-left: 20px;
  width: 49px;
  height: 49px;
  border-radius: 50%;
}

.account {
  width: 70%;
  color: #fff;
  margin-left: 10px;
  align-items: center;
}

.nick-name{
  font-family: 'Mcrosoft Yahei';
  font-size: 16px;
}

.address{
  font-size: 13px;
}
.nav {
  width: 15px;
  color: #fff;
}
複製代碼

可能存在的一些問題

  • 其餘用戶發佈的內容,有時候顯示不出來? 將數據庫的權限設置爲所有人可見。
  • 發佈內容以後返回首頁沒有自動刷新? 在廣場首頁 onShow 的時候獲取數據庫的數據進行展現。
  • clone 源碼後運行不起來? 須要在本身的雲數據庫中建立對應的表。
相關文章
相關標籤/搜索