使用Taro框架開發(fā)小程序
最近一直在做小程序項目的開發(fā),上手直接就是wepy, 風格跟vue差不多,整體上,還算穩(wěn)定,開發(fā)起來比原生的效率要高一點;很多人也知道,mpvue就是用vue搭建的,但始終覺得,失去了路由的vue,就像失去了靈魂;雖然接下來要給大家安利的框架,也貌似失去了該靈魂- taro框架( Taro 是一套遵循React 語法規(guī)范的 多端開發(fā) 解決方案。)
taro開發(fā)文檔: nervjs.github.io/taro/docs/R…
有興趣的可以去看看,在這里我將我初步入坑的學習過程,以及構建了大致礦建與大家分享下:
一:安裝 Taro 開發(fā)工具 @tarojs/cli
npm install -g @tarojs/cli 復制代碼二:使用命令創(chuàng)建模板項目
taro init taro-react-mini-program 復制代碼
可以根據(jù)自己的需要,選擇是否使用ts, sass或者less, 接著等安裝好依賴,項目就構建完成;
三:項目目錄結構├── dist 編譯結果目錄 ├── config 配置目錄 | ├── dev.js 開發(fā)時配置 | ├── index.js 默認配置 | └── prod.js 打包時配置 ├── src 源碼目錄 | ├── pages 頁面文件目錄 | | ├── index index頁面目錄 | | | ├── index.js index頁面邏輯 | | | └── index.css index頁面樣式 | ├── app.css 項目總通用樣式 | └── app.js 項目入口文件 └── package.json 復制代碼
框架的使用和注意事項,文檔中有介紹,我這邊主要寫一些項目配置和踩過的坑;
這里需要先安裝一些依賴
npm install tslint stylelint tslint-config-prettier -D 復制代碼
代碼規(guī)范 .prettierrc
{
"stylelintIntegration": true,
"tslintIntegration": true,
"tabWidth": 2,
"singleQuote": true,
"semi": false
}
復制代碼
.prettierignore
/**/libs/** dist/ lib/ 復制代碼
樣式規(guī)范: .stylelintrc.js
module.exports = {
ignoreFiles: ['**/*.md', '**/*.ts', '**/*.tsx', '**/*.js']
}
復制代碼
.stylelintignore
**/dist 復制代碼
tslint.json
{
"extends": ["tslint:recommended", "tslint-config-prettier"],
"rules": {
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-access": false,
"member-ordering": false,
"no-empty-interface": false,
"no-console": [true, "warning"],
"interface-name": [true, "never-prefix"],
"no-empty": false,
"quotemark": [true, "single"]
// "semicolon": [false], // 結尾比較分號
// "trailing-comma": [false], // 結尾必須逗號
// "requireForBlockBody": true,
}
}
復制代碼
接著配置git的提交commit提交驗證,需要安裝對應的依賴包,可以從我的另外一篇文章看:
juejin.im/post/5b9867…
再加上自己配置一個.gitignore文件,就這樣,我們將大致需要的配置文件都配置好了;看看效果:
當有不規(guī)范的代碼提交的時候
把所有問題都解決之后提交,當然tslint以及其他的一些配置都是自定義的,可以自己配置。覺得麻煩的可以根據(jù)自己的“口味”配置項目
然后我們就可以愉快的開發(fā)我們的項目,運行npm run dev:weapp,打開我們的小程序
很多人反饋用原生的 Taro.request或者用第三方axios等等做異步請求總會有錯,我沒親測,但是自己用promise封裝了方法, 在根目錄src文件夾下創(chuàng)建utils文件夾, 在這里我簡單的模擬微信授權登錄,以及檢測session是否過期,綁定用戶的場景寫一個大概例子,接口為虛構:
├── utils | ├── api.ts 請求接口設置 | ├── http.ts http公共請求文件 | └── index.ts 復制代碼
http.ts代碼如下:
import Taro from '@tarojs/taro'
import md5 from 'blueimp-md5'
type HttpMethods = 'GET' | 'POST' | 'PUT' | 'DELETE'
// 后端是否支持json格式
const contentType = 'application/x-www-form-urlencoded'
// const contentType = 'application/json'
export default class Http {
noNeedToken = ['mockFakeApi']
get(url: string, data: object) {
return this.commonHttp('GET', url, data)
}
post(url: string, data: object) {
return this.commonHttp('POST', url, data)
}
async commonHttp(method: HttpMethods, url: string, data: object) {
return new Promise<any>(async (resolve, reject) => {
Taro.showNavigationBarLoading()
try {
const res = await Taro.request({
url,
method,
data,
header: {
'content-type': contentType
}
})
Taro.hideNavigationBarLoading()
switch (res.statusCode) {
case 200:
return resolve(res.data.response)
default:
console.log(res.data.message)
reject(new Error(res.data.msg))
}
} catch (error) {
Taro.hideNavigationBarLoading()
reject(new Error('網(wǎng)絡請求出錯'))
}
})
}
}
復制代碼
api.ts
import Http from './http' const http = new Http() // 自動登錄 const url = 'xxxxx' export const login = (data: object) => http.post(url, data) 復制代碼
index.ts (自定義公共處理接口文件)
import Taro from '@tarojs/taro'
import { login } from './api'
// 獲取微信登錄憑證
export const wxLogin = async () => {
try {
const res = await Taro.login()
return res.code
} catch (error) {
console.log('微信獲取臨時憑著失敗')
}
}
export const userLogin = async () => {
try {
await Taro.checkSession()
if (!Taro.getStorageSync('token')) {
throw new Error('本地沒有緩存token')
}
} catch (error) {
const code = await wxLogin()
const loginRes: any = await login({
code
// ...(其他參數(shù))
})
console.log('用戶數(shù)據(jù)', loginRes)
}
}
復制代碼
最后在pages/index/index.tsx中引用就好了
import { userLogin } from '../../utils/index'
....
async componentDidMount() {
await userLogin()
}
復制代碼
整個框架的使用大致就是這樣了,react的書法風格還是挺舒服的,如果習慣了vue的寫法可能剛開始會不習慣,有興趣的可以嘗試嘗試,下面再簡單的把一些小技巧給補上:
一:圖片以模塊的方式的引入使用ts搭建的項目,引入靜態(tài)資源,比如圖片,會提示找不到模塊,這時候就必須將圖片聲明為一個模塊:
在types目錄的global.d.ts文件下:
declare module ‘*.png’ {
? const img: any
? export default img
}
二:動態(tài)添加style
<View style={{backgroundImage: `url(${bgImg})`}}></View>
復制代碼
三:動態(tài)添加class
1.<View className={data.length>0?’class-yes’: ’class-no'}></View>
2.<View className={`common ${data.length>0?’class-yes’: ’class-no}`}></View>
復制代碼
四:this的指向問題
1)在 Taro 的頁面和組件類中, this 指向的是 Taro 頁面或組件的實例,如果我們要引用原生組件,需要使用到this的時候,如果如下引用:
Taro.createCanvasContext(canvasId, this.$scope)
wx.createLivePlayerContext(liveId, this.$scope)
錯誤:wx.createLivePlayerContext(liveId, this)這樣引入是沒有效果的,this并不是指向 wx.createLivePlayerContext.
(當前版本沒有l(wèi)iveplayer的回調方法,所以直接用原生wx)
第二部分:如何開通一個小商店

立即掃碼關注

多門店/直營/加盟連鎖管理系統(tǒng)