小程序云开发学习

本篇博客主要是对 小程序如何用云数据库增删改查

01.背景

1.无需搭建服务器,快速构建小程序、公众号 2.免登录、免鉴权调用微信开放服务 ● 云开发可以通过云函数直接调用微信开放api,免去了登录、鉴权等一些列复杂的前置操作,这一步大大的降低了开发的成本 3.云存储 ● 云开发提供了一块存储空间,提供了上传文件到云端、带权限管理的云端下载能力,前端开发可以在小程序端和云函数端通过 API 使用云存储功能。也就是说文件存储这一块功能可以由前端独自完成,只需将云存储返回的fileId传给后端写入到数据库即可。

02配置云环境

1.在小程序端开始使用云能力前,需要调用wx.cloud.init方法对云能力进行初始化

// app.js
App({
    onLaunch() {
        wx.cloud.init({
            env: "hlc-utga0"
        })
        this.getOpenid();
    },

    globalData: {
        userInfo: {
            openid: wx.getStorage({
                key: 'openid'
            })
        }
    }
})

字段env表示自己在与云数据库中的环境ID.

2.在跟目录中创建云函数目录的文件夹

enter description here

3.在project.config.json文件中指定云函数的目录

enter description here

03添加数据

enter description here

以下是wxss,wxml

/* pages/add/add.wxss */


.chooseimg {
    border-bottom: 15rpx solid #beb8b8;
    padding: 15rpx;
}

.choose-tit {
    display: block;
    font-size: 32rpx;
    font-weight: bold;
    color: #1a1a1a;
}

.tip {
    font-size: 28rpx;
    color: #beb8b8;
    font-weight: 400;
}

.choose-box {
    display: inline-block;
    max-width: 200rpx;
    text-align: center;
    background: #f7f3f3;
    padding: 20rpx 0;
    margin: 20rpx 0;
}

.choose-box image {
    width: 64rpx;
    height: 64rpx;
}

.choose-box text {
    display: block;
    font-size: 32rpx;
    color: #beb8b8;
}

.infobox {
    padding: 30rpx 15rpx;
}

.ipttxt {
    display: flex;
    justify-content: space-between;
    color: #beb8b8;
    font-size: 32rpx;
    margin: 30rpx 0;
}

input {
    display: inline-block;
    text-align: right;
    vertical-align: middle;
}

input::placeholder {
    color: #beb8b8;
}

.upload {
    width: 500rpx;
    height: 80rpx;
    margin: auto;
    text-align: center;
    background: rgb(155, 156, 154);
    border-radius: 20rpx;
    color: #f7f3f3;
    line-height: 80rpx;
}

.preview {
    display: inline-block;
    margin: 20rpx 20rpx 20rpx 0;
}

.preview image {
    width: 200rpx;
    height: 200rpx;
}

.cover {
    display: flex;
    justify-content: space-between;
    height: 100rpx;
    line-height: 100rpx;
}

.cover image {
    width: 50rpx;
    height: 50rpx;
    vertical-align: middle;
}

.cover input {
    width: 60rpx;
}
<view class="container">
    <view class="chooseimg">
        <text class="choose-tit">上传曲谱 <text class="tip">(至多9张)</text></text>
        <view class="preview" wx:for="{{imgList}}" wx:key="item">
            <image src="{{item}}" mode="aspectFit"></image>
        </view>
        <view class="choose-box" bindtap="chooseImage">
            <image src="/images/icons/up-icon.png"></image>
            <text>添加新图片</text>
        </view>
    </view>
    <view class="infobox">
        <view class="ipttxt">
            <text>曲谱名称</text> <input type="text" bindinput="getname" placeholder="必填 请输入" />
        </view>
        <view class="ipttxt">
            <text>乐器</text> <input type="text" bindinput="getmusical" placeholder="必填 请输入" />
        </view>
        <view class="ipttxt cover">
            <text>封面</text>
            <view>
                <image src="{{coverurl}}"></image> <input type="text" placeholder="选填" bindtap="upcoverimg" />
            </view>
        </view>
        <view class="ipttxt">
            <text>作者</text> <input type="text" bindinput="getauth" placeholder="选填" />
        </view>
        <view class="ipttxt">
            <text>曲谱类型</text> <input type="text" bindinput="gettype" placeholder="选填" />
        </view>
    </view>
    <view class="upload" bindtap="upinfo">上传</view>
</view>

接下来就是js逻辑

1.首先需要在云数据库中创建保存数据的集合

enter description here

其中的_id是自动生成的,_openid是当前用户的唯一标识,后续可以通过查询_openid来写当前用户自己创建的文件。

2.接下来可以通过页面Js关联云数据库中的集合,也可以通过云函数去关联,我是直接用当前页面的js

// pages/add/add.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgList: [],
        coverurl: '',
        info: {
            openid: '',
            name: '',
            musical: '',
            auth: '',
            type: '',
            cover: [],
            urlList: [],
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },
    // 选择图片封装
    chooseImageFunction(num, localurl, dataurl) {
        let that = this;
        wx.chooseImage({
            count: num,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: res => {
                wx.showLoading({
                    title: '上传中',
                })
                setTimeout(function () {
                    wx.hideLoading()
                }, 2000)
                //    让选择图片展示在页面上,方便用户预览
                // tempFilePath可以作为 img 标签的 src 属性显示图片
                const tempFilePaths = res.tempFilePaths;
                this.setData({
                    [localurl]: tempFilePaths
                })
                for (let i = 0; i < tempFilePaths.length; i++) {
                    let imgurl = tempFilePaths[i];
                    // 指定云数据库中的文件夹以及文件名
                    const cloudPath = 'guitar/' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000) + tempFilePaths[i].match(/\.[^.]+?$/)
                    that.uploadimg(imgurl, cloudPath, dataurl)
                }
            }
        })
    },
    // 上传图片函数
    uploadimg(filePath, cloudPath, dataurl) {
        wx.cloud.uploadFile({
            cloudPath, // 上传至云端的路径
            filePath, // 小程序临时文件路径
            success: res => {
                wx.showToast({
                    title: '上传成功',
                })
                // 获取云存储中的图片地址
                dataurl.push(res.fileID);
            },
            fail: console.error
        })
    },
    // 上传曲谱
    chooseImage() {
        this.chooseImageFunction(9, 'imgList', this.data.info.urlList)
    },
    // 上传封面
    upcoverimg() {
        this.chooseImageFunction(1, 'coverurl', this.data.info.cover)
    },
    // 
    // 获取输入框的值
    getname(event) {
        this.data.info.name = event.detail.value
    },
    getmusical(event) {
        this.data.info.musical = event.detail.value
    },
    getauth(event) {
        this.data.info.auth = event.detail.value
    },
    gettype(event) {
        this.data.info.type = event.detail.value
    },

    upinfo() {
        if (this.data.info.name != '' && this.data.info.musical != '') {
            const info = this.data.info
            wx.cloud.database().collection('Pedigree').add({
                data: {
                    auth: info.auth,
                    name: info.name,
                    cover: info.cover,
                    type: info.type,
                    imgList: info.urlList
                }
            }).then(res => {
                wx.showToast({
                    title: '添加成功',
                })
            }).catch(err => {
                wx.showToast({
                    title: '添加失败',
                })
            })
        } else {
            wx.showToast({
                title: '请填写必填项',
            })
        }
    },
})

其中的字段cover代表的是封面,urlList表示上传的谱子图,集合中本身没有保存图片,只是保存了在云存储中的fileId, 也就是在云存储中的图片地址。这样就简单实现了如何向云数据库中添加数据

04获取数据

获取云数据库中的数据,直接通过新建云函数,比如在云函数目录中新建getOpenid云函数,就可以获取到当前用户的唯一标识

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

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()

    return {
        event,
        openid: wxContext.OPENID,
        appid: wxContext.APPID,
        unionid: wxContext.UNIONID,
    }
}

然后在app.js中调用该云函数并且保存在本地,这样我们就可以通过openid去筛选当前用户自己上传的数据

    // 获取openid
    getOpenid() {
        wx.cloud.callFunction({
            name: 'getOpenId',
            success(res) {
                wx.setStorageSync('openid', res.result.openid)
            },
            fail(res) {
                console.log(res);
            }
        })
    },

比如我们希望去获取Pedigree集合中的数据

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

cloud.init()

const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
    // 只获取当前自己用户的
    return await db.collection('Pedigree').where({
        _openid: event._openid
    }).get()
}

然后通过页面去调用该云函数,即刻获取数据