午夜91福利视频,午夜成人在线观看,午夜在线视频免费观看,午夜福利短视频,精品午夜成人免费视频APP

小程序模板網

小程序云開發初體驗

發布(bu)時間:2018-11-15 17:11 所屬欄目:小程序開發教程

 

創建云開(kai)發(fa)項目(mu)時,據官方描述,在微信(xin)開(kai)發(fa)工具(ju)里,有一個QuickStart選(xuan)項,但我發(fa)現并沒有,可能(neng)是開(kai)發(fa)工具(ju)版本或其他原因。

給數據庫添加數據

我在貓眼電影(ying)拷(kao)貝了(le)部分數據,準備倒入小程序(xu)云開發的(de)數據庫

 

 

可以看到,在控制臺,可以自行添加數據,也可以直(zhi)接倒入(ru)一個json文件(jian)。我這里(li)選(xuan)擇(ze)調用它的API去(qu)倒入(ru)貓眼json數據

首先(xian)我創建了一個名為movies的集合,緊接著調用初始化的方法

app.js

...
onLaunch: function () {
    wx.cloud.init()
}
...
復制代碼

要(yao)(yao)操(cao)作數據庫,需要(yao)(yao)先獲取到(dao)數據庫引用, 同時,獲取到(dao)我(wo)剛創建的movies集(ji)合的引用, 由于在其他頁面也需要(yao)(yao)調(diao)用,我(wo)這里把它(ta)們都掛到(dao)app的屬(shu)性(xing)上

const app = getApp()
...
app.$db = wx.cloud.database()
app.$collect_movies = app.$db.collection('movies')
...
復制代碼
最后, 調用添加的方法

data.subjects.forEach(o => {
  app.$collect_movies.add({
    data: o
  })
})
復制代碼
現在云開發控制臺數據庫里已經有添加的數據了

顯示所有電影
app.$collect_movies.where({
  _openid: 'ofgUd0Rb4w8E7Af40N46ExxozS5g'
}).get({
  success: function (res) {
    console.log('res', res)
    that.setData({
      movies: res.data
    })
  }
})
復制代碼
根據ID查詢指定電影
app.$collect_movies.doc('W8Wf4t2AWotkhlzK').get({
    success: function (res) {
      console.log('res',res)
      that.setData({
        movie: res.data
      })
    }
})
復制代碼
查詢9分以上的電影
const _ = app.$db.command
app.$collect_movies.where({
    sc: _.gte(9)
}).get({
    success: function (res) {
      wx.hideLoading()
      that.setData({
        movies: res.data
      })
    }
})
獲取9分以上或0分的電影
const _ = app.$db.command
app.$collect_movies.where({
    sc: _.eq(0).or(_.gte(9))
}).get({
    success: function (res) {
      wx.hideLoading()
      that.setData({
        movies: res.data
      })
    }
})
復制代碼
修改主演名
# 確認修改
const that = this
app.$collect_movies.doc(this.currentMovieId).update({
  data: {
    star: this.data.actor
  },
  success: function (res) {
    that.initUpdateData()
  }
})
復制代碼
刪除一部電影
# 確定刪除
delAction(e) {
    const that = this
    const id = e.currentTarget.dataset.id
    app.$collect_movies.doc(id).remove({
      success: function (res) {
        that.initUpdateData()
      }
    })
}
復制代碼

文件管理

上傳圖片到云存儲

試(shi)著把(ba)手機相冊的圖(tu)片上(shang)傳(chuan)到小(xiao)程(cheng)序云存儲中,可以在小(xiao)程(cheng)序端直接使用提供的api

wx.cloud.uploadFile({
  cloudPath: 'example.png', // 上傳至云端的路徑
  filePath: '', // 小程序臨時文件路徑
  success: res => {
    // 返回文件 ID
    console.log(res.fileID)
  },
  fail: console.error
})
復制代碼
如果單純從代碼量來看,比上傳到騰訊自家騰訊云還簡單,當然比上傳到像阿里云、七牛云這樣的平臺操作更簡單。

上傳成功之后,返回的不是圖片url, 而是文件id。如果要顯示圖片或者播放視頻,這個文件id,小程序的組件image/video也能識別

 <image class="movie" mode="widthFix" src="{{ fileId }}" wx:if="{{ fileId }}"> </image>
復制代碼
upload() {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths[0])
        wx.cloud.uploadFile({
          cloudPath: 'test/2.png', // 上傳至云端的路徑
          filePath: tempFilePaths[0], // 小程序臨時文件路徑
          success: res => {
            // 返回文件 ID
            console.log(res.fileID)
            that.setData({
              fileId: res.fileID
            })
          },
          fail: console.error
        })
      }
    })
}


 

根據文件id下載文件
downloadFile() {
  wx.cloud.downloadFile({
  fileID: 'cloud://ii-1853ca.6969-ii-1853ca/test/2.png',
  success: res => {
    // 返回臨時文件路徑
    console.log('tempFilePath', res)
    // cloud://ii-1853ca.6969-ii-1853ca/test/2.png
    this.setData({
      downloadFileResult: res
    })
  },
  fail: err => {
    // handle error
  }
})
復制代碼

根據文件id換取臨時網絡鏈接

可以根據文件(jian) ID 換取臨時(shi)文件(jian)網絡鏈接(jie),文件(jian)鏈接(jie)有(you)有(you)效期(qi)為兩個小時(shi)

const that = this
wx.cloud.getTempFileURL({
    fileList: [this.data.fileId],
    success: res => {
      // //6969-ii-1853ca-1253918415.tcb.qcloud.la/test/2.png
      that.setData({
        fileList: res.fileList
      })
    },
    fail: err => {
      // handle error
    }
})
復制代碼

云函數

怎(zen)么(me)玩(wan)?

云函數是(shi)運(yun)行在Node.js環境下的

首先在小程序項(xiang)目(mu)根(gen)目(mu)錄(lu)(lu)找到配置(zhi)文件project.config.json文件,加(jia)上一(yi)個配置(zhi), 指定本(ben)地已存在的目(mu)錄(lu)(lu)作(zuo)為云(yun)函數的本(ben)地根(gen)目(mu)錄(lu)(lu)

  "cloudfunctionRoot": "./functions/",
復制代碼

指定(ding)之后神奇的一幕就是圖標(biao)(biao)會變成 &ldquo;云目錄圖標(biao)(biao)”

子目錄都是(shi)我(wo)通過右鍵菜單(dan)創建一個新(xin)的云函數,其(qi)中文件名就是(shi)云函數名

 每(mei)創建一個云函數,都(dou)會(hui)出現彈窗(chuang),詢問你是(shi)否有node環(huan)境,確定后(hou)會(hui)自動打開終(zhong)端,安裝依賴(lai), 所以每(mei)一個云函數里面都(dou)是(shi)這樣的:

在index.js中, 默認是這樣(yang)的(de)

// 云函數入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函數入口函數
exports.main = async (event, context) => {

}
復制代碼
創建一個相加的云函數
plus/

// 云函數入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函數入口函數
// context 對象包含了此處調用的調用信息和運行狀態
// event 指的是觸發云函數的事件
exports.main = async (event, context) => {
  return {
    sum: event.a + event.b
  }
}
復制代碼
在小程序端調用plus云函數, 參數名一眼就看明白,不用解釋

wx.cloud.callFunction({
  name: 'plus',
  data: {
    a: 1,
    b: 2,
  },
  success: function (res) {
    console.log('plus', res.result) // 3
  },
  fail: console.error
})
復制代碼

調用后報(bao)錯,是(shi)因為沒有把創建的云函數(shu)上傳部(bu)署到云端, 如何部(bu)署?看(kan)下圖(tu)

部署(shu)成(cheng)功(gong)之(zhi)后,我們(men)來到云控制臺(tai), 發現(xian)云函數已(yi)經在(zai)上(shang)面(mian)

 

 

回(hui)到小程序,再次調用云(yun)函數,發(fa)現已經可以了, 拿到了預期的值3

獲取小程序用戶信息

云開(kai)發(fa)的云函(han)(han)數的獨特優勢在于與微(wei)信登錄鑒(jian)權(quan)的無(wu)縫(feng)整合。當小程(cheng)序端調用云函(han)(han)數時,云函(han)(han)數的傳入參數中(zhong)會被注入小程(cheng)序端用戶的 openid,開(kai)發(fa)者(zhe)無(wu)需校驗 openid 的正確性,因為微(wei)信已經完成了這(zhe)部分(fen)鑒(jian)權(quan),開(kai)發(fa)者(zhe)可以直接(jie)使用該 openid。與 openid 一起同時注入云函(han)(han)數的還有小程(cheng)序的 appid

定義云(yun)函數(shu)

// 云函數入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函數入口函數
exports.main = async (event, context) => {
  return event.userInfo
}
復制代碼
調用云函數

wx.cloud.callFunction({
    name: 'userInfo',
    success: function (res) {
      console.log('userInfo', res.result)
        /*
          {
            appId:"wx8dae61dd0ef5c510",
            openId:"ofgUd0Rb4w8E7Af40N46ExxozS5g"
           }
        */
    },
    fail: console.error
})
復制代碼
異步云函數
// 云函數入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函數入口函數
exports.main = async (event, context) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(event.a + event.b)
    }, 3000)
  })
}
復制代碼

在(zai)云函(han)數中(zhong)我們可以(yi)(yi)引(yin)入第三方(fang)依賴來(lai)幫助我們更快的(de)(de)開發。云函(han)數的(de)(de)運(yun)行(xing)(xing)環境是 Node.js,因此我們可以(yi)(yi)使(shi)用(yong) npm 安裝(zhuang)第三方(fang)依賴。比(bi)如除了使(shi)用(yong) Node.js 提供的(de)(de)原(yuan)生 http 接(jie)口在(zai)云函(han)數中(zhong)發起(qi)網(wang)(wang)絡請(qing)求,我們還可以(yi)(yi)使(shi)用(yong)一個流行(xing)(xing)的(de)(de) Node.js 網(wang)(wang)絡請(qing)求庫 request 來(lai)更便捷(jie)的(de)(de)發起(qi)網(wang)(wang)絡請(qing)求。

注意,現(xian)在上傳云函數時(shi)不會在云端自動安裝依賴(lai),需要(yao)開發(fa)者在本地安裝好依賴(lai)后一起(qi)打包上傳。

云函數操作數據庫
// 云函數入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()

// 云函數入口函數
exports.main = async (event, context) => {
  // 獲取電影集合數據
  return db.collection('movies').get()
}
復制代碼
云函數調用其他云函數
定義云函數

// 云函數入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函數入口函數
exports.main = async (event, context) => {
  return await cloud.callFunction({
    name: 'plus',
    data: {
      a: 1,
      b: 2,
    }
  })
}
復制代碼

調用云函(han)數

wx.cloud.callFunction({
  name: 'cloudFuncCallColundFunc',
  complete: res => {
    console.log('cloudFuncCallColundFunc', res)
  },
})
復制代碼
云函數日志、測試

可以看到調用的云函數的調用日志

可以直(zhi)接測試(shi)編寫好的云函數(shu),傳入參數(shu), 點擊(ji)運行調試(shi)按鈕即可

云開發初體驗總結

云開發大概在8月份(fen)公測,9月份(fen)發布出(chu)來(lai)的(de),現(xian)在已經快(kuai)11月份(fen)了(le),據官方描述,有(you)很多開發人員參與進去,是他們(men)沒有(you)預料到的(de), 同時也被提出(chu)了(le)很多吐槽點,小程序的(de)云開發也可以(yi)說是在試水階段(duan),有(you)不少坑,后面肯定會越來(lai)越完善。 逐(zhu)漸(jian)成熟,會是一個非常不錯的(de)解決方案(an), 特(te)別是針對那些初創公司。

 


易優小程序(企業版)+靈活api+前后代碼(ma)開源 碼(ma)云倉(cang)庫:
本文地址://www.jinyoudianli.com/wxmini/doc/course/24959.html 復制鏈接 如需定制請聯系易優客服咨詢:

工作日 8:30-12:00 14:30-18:00
周六及部(bu)分節假(jia)日提供值班服務(wu)

易小優
轉(zhuan)人工(gong) ×