小試小程序云開發(fā)(小結(jié))
微信小程序剛出沒多久時,曾經(jīng)上手寫過demo,但開發(fā)體驗比較差,所以一直沒怎么關(guān)注。不過自從諸多適配方案出爐,以及云端的開通,覺得還是有必要上手體驗一番的,于是為我的技術(shù)博客也寫了個小程序版。
原生開發(fā)我是不想再試了,那就選一種適配方案,目前比較知名的有基于vue的 mpvue,umi-app,基于react 的 taro,以及TX團體出的全新框架 wepy。個人對 react 的好感 以及 taro 框架的走向成熟,促使我選擇了 taro。
云端開發(fā)就是將普通小程序的傳統(tǒng)后端切換為微信提供的 輕量級云端。而這個云端服務(wù)部分的開發(fā)其實是針對前端開發(fā)的,前端工程師很容易就能全棧開發(fā)出一整個小程序。但是這種輕量級解決方案也只是針對業(yè)務(wù)簡單的項目,因為公共平臺肯定有各種限制,它的出現(xiàn)只是讓我們多了一個選擇方案而已。
接著進入主題,項目大體目錄結(jié)構(gòu)如下
client #前端目錄 ├── config #配置 ├── dist #輸出 ├── src #源目錄 └── index.html #入口文件 cloud #云目錄 ├── dao #數(shù)據(jù)庫操作函數(shù)集合 ├── login #登錄云函數(shù) └── ... #其他
前端
小程序的前端部分,想必不用過多講解,因為這都是前端的基本功。就以首頁為樣例,使用了typeScript,主要功能是分頁加載數(shù)據(jù),調(diào)用微信提供的觸發(fā)到達底部的api-onReachBottom即可。
import Taro, { Component, Config } from "@tarojs/taro";
import { View, Text, Navigator } from "@tarojs/components";
import "./index.scss";
interface IState {
loading: boolean;
size: number;
page: number;
total: number;
list: Array<{ _id: string; summary: object }>;
context:object;
}
export default class Index extends Component<{}, IState> {
state = {
loading: false,
size: 10,
page: 0,
total: -1,
list: [],
context:{}
};
config: Config = {
navigationBarTitleText: "Jeff's Blog",
onReachBottomDistance: 50
};
componentWillMount() {
this.getList();
this.getLogin();
}
getDbFn(fn, param) {
return Taro.cloud.callFunction({
name: "dao",
data: { fn, param }
});
}
onReachBottom() {
this.getList();
}
getList() {
const { size, page, total, loading } = this.state;
if (loading) return;
Taro.showLoading({ title: 'loading', });
if (total >= 0 && size * page >= total) return;
this.setState({ loading: true });
this.getDbFn("getList", { size, page: page + 1 }).then(res => {
Taro.hideLoading();
const total = res.result.total;
const list = this.state.list.concat(res.result.list);
this.setState({ loading: false, page: page + 1, total, list });
}).catch(err => {
Taro.hideLoading();
this.setState({ loading: false });
});
}
onShareAppMessage (res) {
return {
title: "Jeff's Blog",
path: '/pages/index/index'
}
}
render() {
return (
<View className='container'>
{this.state.list.map(l => (
<View className='item' key={l._id}>
<Navigator url={'/pages/post/post?id=' + l._id}>
<Image className='banner' mode='widthFix' src={l.summary.banner} />
<View className='title'>{l.summary.title}</View>
</Navigator>
<View className='sub-title'>
{l.summary.tags.map(t => (
<Navigator className='tag' url={'/pages/list/list?tag=' + t}> {t} </Navigator>
))}
<Text className='time'>{l.summary.date}</Text>
</View>
</View>
))}
</View>
);
}
}
與普通小程序不同的地方就是調(diào)用云端,云函數(shù)調(diào)用如官方樣例所示
getLogin(){
Taro.cloud.callFunction({
name: "login",
data: {}
}).then(res => {
this.setState({ context: res.result });
}).catch(err=>{
});
}
云端
云端數(shù)據(jù)庫是個文檔型,操作風(fēng)格與mongodb如出一轍,格式自然是json。最有用的還是操作數(shù)據(jù)庫的部分,操作方法都已經(jīng) Promise 化,調(diào)用還是比較方便的。具體內(nèi)容請查看文檔: 小程序云開發(fā)
//數(shù)據(jù)庫引用
const db = wx.cloud.database()
//獲取數(shù)據(jù)集合
const todos = db.collection('todos')
//獲取記錄數(shù)
todos.count();
//條件查找
todos.where({done: false,progress: 50}).get()
//插入
todos.add({data: {content:'11',time:new Date()}},success:(res){});
//更新
todos.doc('todo').update({ data: { done: true}},success:(res){});
//刪除
todos.where({done:true}).remove();
//分頁查找
todos.orderBy('time','desc')
.skip(start)
.limit(size)
.get();
云函數(shù)
調(diào)用云端的方式就要使用云函數(shù),就以下面數(shù)據(jù)庫操作庫為例
// 云函數(shù)入口文件
const cloud = require("wx-server-sdk");
cloud.init();
// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
const { fn, param } = event;
return dao[fn](param);
};
// 調(diào)用數(shù)據(jù)庫
const db = cloud.database();
// 表
const posts = db.collection("posts");
const tags = db.collection("tags");
const dao = {
async getList({ page = 1, size = 10 }) {
const start = (page - 1) * size;
try {
const { total } = await posts.count();
const { data } = await posts
.field({ summary: true })
.orderBy('num','desc')
.skip(start)
.limit(size)
.get();
return {
code: 0,
list: data,
total,
message: "sucess"
};
} catch (err) {
return {
code: -1,
list: [],
total: -1,
err: err,
message: "error"
};
}
},
getPost({ id }) {
return posts.doc(id).get();
},
async getTagList({ tag }) {
try{
const { data } = await tags.where({ name: tag }).get();
if(!data.length){
return {
code:0,
list:[],
message: "success"
};
}
const list = data[0].list.sort((a,b) => b.num - a.num);
return {
code:0,
list:list,
message: "success"
};
} catch(err){
return {
code: -1,
list:[],
err: err,
message: "error"
};
}
}
}
將操作數(shù)據(jù)庫的所有云函數(shù)合并成一個文件,將云函數(shù)入口封裝一下,即把函數(shù)名字和參數(shù)都做為參數(shù)
exports.main = async (event, context) => {
const { fn, param } = event;
return dao[fn](param);
};
對應(yīng)前端部分也封裝出一個調(diào)用數(shù)據(jù)庫的方法
getDbFn(fn, param) {
return Taro.cloud.callFunction({
name: "dao",
data: { fn, param }
});
}
云端部分開發(fā)完之后,在微信開發(fā)者工具里面上傳云端代碼即可,而其余部分的流程和普通小程序一樣,這里也不再介紹。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
echarts實現(xiàn)橫向和縱向滾動條(使用dataZoom)
這篇文章主要給大家介紹了關(guān)于echarts使用dataZoom實現(xiàn)橫向和縱向滾動條的相關(guān)資料,最近項目中使用到echarts圖表,當(dāng)數(shù)據(jù)過多時需要添加橫向滾動條,需要的朋友可以參考下2023-08-08
通過設(shè)置CSS中的position屬性來固定層的位置
position 屬性規(guī)定元素的定位類型,這個屬性定義建立元素布局所用的定位機制,本文給大家介紹通過設(shè)置CSS中的position屬性來固定層的位置,感興趣的朋友一起學(xué)習(xí)吧2015-12-12
JavaScript函數(shù)式編程實現(xiàn)介紹
函數(shù)式編程是一種編程范式,將整個程序都由函數(shù)調(diào)用以及函數(shù)組合構(gòu)成。 可以看成一條流水線,數(shù)據(jù)可以不斷地從一個函數(shù)的輸出流入另一個函數(shù)的輸入,最后輸出結(jié)果2022-09-09

