mpvue開發小程式總結
阿新 • • 發佈:2018-12-07
一、對小程式自身的封裝
1.1.wx.request()的promise封裝(併發請求不能超過五個)
export const request = (url, data, method) => {
return new Promise((resolve, reject) => {
const accessToken = wx.getStorageSync('accessToken')
const header = {
'Content-Type': 'application/json',
'token' : accessToken // 所有請求將token放在header裡傳輸
}
wx.request({
url,
data,
method,
success(res) {
if (res.data.success) {
resolve(resp)
} else {
if(res.data.errorCode === 401) { // token錯誤特殊邏輯(code碼跟後端約定)
const url = "../login/main"
wx.redirectTo({ url })
wxToast('登入失效,請重新登入')
return
}
wxToast(res.errorMessage || '服務異常,請稍後再試') // 錯誤統一以toast形式彈出
reject(res.data) // 並將錯誤丟擲以便在catch中處理一些特殊業務邏輯
}
},
fail(res) {
reject(res)
wxToast(res.errorMessage || '服務異常,請稍後再試' )
console.log(res)
}
})
})
}
//呼叫:
const url = 'https://xxx'
export const login = params => request(`${url}/xxx`, params, 'POST'); // 登入
login(params).then(data => {
console.log('success')
}).catch(e => {
console.log('failed')
})
複製程式碼
1.2 toast的封裝
export const wxToast = (title='',icon='none',duration=2000) => {
wx.showToast({
title,
icon,
duration
})
}
複製程式碼
1.3 storage的封裝
export const wxStorage = (key, data) => {
if(data) { // data存在,則是設定
wx.setStorage({
key,
data
})
} else {
wx.getStorageSync(key)
}
}
複製程式碼
二、mpvue小程式採坑
2.1 vue的created鉤子
所有頁面的created鉤子在onLaunch後就執行了,所以頁面裡使用created鉤子函式是拿不到實時資料的,故created一般情況下不使用。可用小程式的onReady或onLoad代替
2.2 vue的mounted鉤子
退出再進來頁面後mounted裡的資料並沒有重置(頁面跳轉後並沒有銷燬頁面例項,而是將其推入頁面棧中,所以會儲存之前的舊的資料),將會導致一系列資料錯誤,可用小程式的onShow代替(在onShow裡初始化資料 或者在onUnLoad裡銷燬資料)
2.3 使用者拒絕授權後 重新授權
小程式官方已經禁止 主動跳轉設定頁了,必須在button上觸發(類似獲取使用者資訊wx.getUserInfo()首次也是無法主動喚起授權操作,必須在button上繫結@getuserinfo函式)
- 預授權
const that = this
wx.getSetting({
success (res) {
console.log('點選查詢使用者錄音許可權', res.authSetting['scope.record'])
if (!res.authSetting['scope.record']) {
// 如果使用者之前已經同意授權,則不會出現彈窗,直接返回成功
wx.authorize({
scope: 'scope.record',
success () {
that.isAuth = true
},
fail () { // 主動授權失敗後引導使用者開啟許可權設定頁
that.isAuth = false
}
})
} else {
that.isAuth = true
}
}
})
複製程式碼
- 使用者點選 需要授權的操作時(點選的必須是button,否則wx.openSetting()無法喚起許可權設定頁)
if (!this.isAuth) {
wx.openSetting()
return
}
複製程式碼
2.4 不支援template中使用複雜渲染函式,可用computed計算屬性替代
<template>
<div> {{format(a)}} </div> // 不支援使用渲染函式format
<div>{{b}}</div> // 使用計算屬性(若是一個數組列表,只能先轉譯陣列)
</template>
<script>
export default {
data() {
return {
a:1
}
}
methods: {
format(e) {
return `${e}bbb`
}
},
computed: {
b() {
return `${this.a}bbb`
}
}
}
</script>
複製程式碼
2.5 class/style 不支援 vue 的 classObject/styleObject, 但支援如下形式:
<p class="static" :class="{ active: isActive, 'text-danger': hasError }">222</p>
<p class="static" :class="[isActive ? activeClass : '', errorClass]">444</p>
:style="{transform: 'translate('+ (item.ansId==currentTouchId ? xAxis : 0) + 'px,'+ ((item.ansId==currentTouchId ? yAxis : 0)) +'px)',width: width + 'px', height: height + 'px'}"
複製程式碼
2.6 css background-image 不支援本地圖片,必須是遠端cdn資源
2.7 用canvas繪圖,生成帶引數的小程式碼的海報用於分享朋友圈
由於 海報圖是放在cdn中,canvas不能操作不在同一域名下的圖片,故由服務端去合成
2.8 跳轉tabBar頁面必須用switchTab
2.9 強制更新
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {
// 請求完新版本資訊的回撥
console.log(res.hasUpdate)
})
updateManager.onUpdateReady(function () {
wx.showModal({
title: '更新提示',
content: '新版本已經準備好,是否重啟應用?',
success: function (res) {
if (res.confirm) {
// 新的版本已經下載好,呼叫 applyUpdate 應用新版本並重啟
updateManager.applyUpdate()
}
}
})
})
複製程式碼
2.10 單獨為每個頁面的設定頁面頭部資訊(main.js中設定)
// main.js
const app = new Vue(App)
app.$mount()
export default {
config: {
navigationBarTitleText: '登入'
}
}
複製程式碼
2.11 獲取掃 帶引數二維碼使用者進來的引數
onLoad(options) {
console.log(decodeURIComponent(options.scene))
}
複製程式碼
2.12 小程式checkbox 點選選中顯示錯亂
<checkbox :value="index" :checked="checkItem.checked" />
// 加上checked屬性,點選修改其boolean值
複製程式碼
2.13 帶引數的自定義分享
<template>
//通過button觸發
<button open-type="share" ></button>
</template>
<script>
onShareAppMessage(res) {
let id = wx.getStorageSync("id");
let title = `${this.name}哈哈哈!` // 可以取到data中的資料
let path = "/pages/xxx/main?sourceId=" + id // 必須是以 / 開頭的完整路徑
let imageUrl = "https:xxx.jpg" // 預設是截圖
return {
title: title,
path: path,
imageUrl: imageUrl
};
}
</script>
複製程式碼
2.14 獲取模板訊息id
<form :report-submit="true" @submit="onClick">
<button @click="onShare('students')" class="applyStu" formType="submit">獲取form_id</button>
</form>
onClick(e){
this.formId = e.mp.detail.formId
}
// 點選一次獲取多個formId:
//https://www.jianshu.com/p/84dd9cd6eaed?_blank
複製程式碼
2.15 分包與主包的配置
{
"pages": [
"pages/index/main",
"pages/logs/main"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "WeChat",
"navigationBarTextStyle": "black"
},
"subPackages": [
{
"root": "pages/subPackages", // 分包根路徑
"pages": [
"index/main"
]
}
]
}
複製程式碼