微信小程序剛出沒多久時,曾經上手寫過demo,但開發體驗比較差,所以一直沒怎么關注。不過自從諸多適配方案出爐,以及云端的開通,覺得還是有必要上手體驗一番的,于是為我的技術博客也寫了個小程序版。
原生開發我是不想再試了,那就選一種適配方案,目前比較知名的有基于vue的 mpvue,umi-app,基于react 的 taro,以及TX團體出的全新框架 wepy。個人對 react 的好感 以及 taro 框架的走向成熟,促使我選擇了 taro。
云端開發就是將普通小程序的傳統后端切換為微信提供的 輕量級云端。而這個云端服務部分的開發其實是針對前端開發的,前端工程師很容易就能全棧開發出一整個小程序。但是這種輕量級解決方案也只是針對業務簡單的項目,因為公共平臺肯定有各種限制,它的出現只是讓我們多了一個選擇方案而已。
接著進入主題,項目大體目錄結構如下
client #前端目錄├── config #配置├── dist #輸出├── src #源目錄└── index.html #入口文件cloud #云目錄├── dao #數據庫操作函數集合├── login #登錄云函數└── ... #其他
前端
小程序的前端部分,想必不用過多講解,因為這都是前端的基本功。就以首頁為樣例,使用了typeScript,主要功能是分頁加載數據,調用微信提供的觸發到達底部的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> ); }}
新聞熱點
疑難解答
圖片精選