前言
作者学习微信小程序开发已经快两年了,目前在线上使用着的产品也有两个。微信小程序的开发体验总体上来说还是没有vue那些体验好的(有部分原因是小程序的社区没有vue完善),但是无论如何都好,事在人为。本文主要收录一些开发上的小技巧,提高开发效率和开发体验。
目录结构
behaviors
熟悉vue开发的都知道vue有mixins混入,而在小程序中,这一概念称为behaviors。
behaviors 是用于组件间代码共享的特性,类似于一些编程语言中的 “mixins” 或 “traits”。
每个 behavior 可以包含一组属性、数据、生命周期函数和方法。组件引用它时,它的属性、数据和方法会被合并到组件中,生命周期函数也会在对应时机被调用。 每个组件可以引用多个 behavior ,behavior 也可以引用其它 behavior 。
//定义
export default Behavior({
properties: {
},
data: {
testData: {}
},
methods: {
/**
* @description 测试方法
*/
testMethods () {
}
}
})
//使用
import my_mixin from "../../utils/mixin"
Component({
behaviors: [my_mixin],
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的方法列表
*/
methods: {
onTap(){
this.$emit('myevent', this.data.myEventDetail)//调用$emit方法
}
}
})
components
自定义组件,开发者可以将页面内的功能模块抽象成自定义组件,以便在不同的页面中重复使用;也可以将复杂的页面拆分成多个低耦合的模块,有助于代码维护。自定义组件在使用时与基础组件非常相似。
//定义
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
}
})
//使用
index.json中注册
{
"usingComponents": {
"index-child": "./components/IndexChild/index",
"index-child2": "./components/IndexChild2/index",
"van-button": "@vant/weapp/button/index",
"van-skeleton": "@vant/weapp/skeleton/index"
}
}
wxml中使用
<index-child />
全局Config
全局新增配置项,使得你的项目更好的维护。通常,我们会把网络请求的baseUrl抽离出来,在面对不同的环境下可以通过一次修改作用于每一个接口。
const BASE_URL = 'http://192.168.0.100:7001/app' //接口请求的基本路径
export default {
BASE_URL,
UPLOAD_URL: `${BASE_URL}api/common/upload` //上传服务器的路径
}
iconfont字体
微信自带的icon是非常有限的,一下教程为如何在微信小程序中引入第三方的icon。
1.访问阿里的iconfont
2.搜索到想要的图标,加入购物车,下载源码
3.把下载的源码的文件拷贝进去我们的小程序根目录中
4.在小程序的样式文件中引入当前文件
5.根据类名使用当前icon
//定义
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.iconxihongshiSVG:before {
content: "\e629";
}
//使用
<text class="iconfont iconxihongshiSVG"></text>
使用第三方npm库
官网已经很清楚啦:npm支持
接口封装
每一个应用都离不开后端的接口请求,随着应用的变大功能变多,接口将会越来越难维护和管理。因此我们需要定义一下规范。
目录规范
关于接口的方法,作者都定义在了models文件夹下,其中包括api模块定义,状态码定义,拦截器定义等。
api拦截器
熟悉axios开发的人都知道,axios封装了拦截器,统一规范起来特别方便;而小程序在fly.js的支持下也是支持的。
class RequestModel {
constructor() {
if (!hasInit) {
this.initFlySetting()
}
}
/**
* @description 初始化Flyio配置,全局的拦截处理
*/
initFlySetting() {
//定义请求的基本路径
hasInit = true;
fly.config.baseURL = config.BASE_URL
//请求拦截器
fly.interceptors.request.use(request => {
//拦截处理
const token = getCache('token');
if (token && !fly.config.headers["Authorization"]) {
request.headers["Authorization"] = token;
}
request.headers["Content-Type"] = "application/x-www-form-urlencoded";
wx.showNavigationBarLoading()
return request
})
//响应拦截
fly.interceptors.response.use(response => {
//拦截处理操作
//console.log('RequestCode', response)
wx.hideNavigationBarLoading()
return response
}, async error => {
codeAction(error.status);
wx.hideNavigationBarLoading()
return Promise.reject(error.response)
})
}
/**
*
* @param {object} params 封装的get请求: url:请求地址 data:请求数据
*/
getRequest(params) {
return fly.get(params.url, params.data)
}
/**
*
* @param {object} params 封装的post请求: url:请求地址 data:请求数据 options:请求额外参数
*/
postRequest(params) {
return fly.post(params.url, params.data, params.options)
}
}
状态码定义
前后端定义统一的状态码
class RequestCode {
//请求状态CODE码
static CODE = {
SUCCESS: {
OK: 200,
CREATED: 201,
DELETE: 204
},
FAIL: {
INVALID_REQUEST: 400, //用户发出的请求有错误,服务器没有进行新建或修改数据的操作,该操作是幂等的
UNAUTHORIZED: 401, //TOKEN失效
FORBIDDEN: 403, //权限不足
NOT_FOUND: 404,
GONE: 410, //用户请求的资源被永久删除,且不会再得到的
OVERLOAD: 413, //请求体过大
UNPROCESABLE_ENTITY: 422, //请求参数错误
INTERNAL_SERVER_ERROR: 500 //服务器错误
}
}
}
export default RequestCode
使用封装好的api
通过引入已经定义好的拦截器和方法的request模块,定义好请求方法并且暴露出去。
import RequestModel from './request/request'
class BaseModel extends RequestModel {
constructor() {
super()
}
login(code) {
return this.postRequest({
url: 'base/login',
data: {
code
}
})
}
}
export default BaseModel
微信API支持promise
微信小程序的api都是通过回调函数的形式的,我们可以通过miniprogram-api-promise库使得他的接口直接promise调用。
//定义
import {
promisifyAll
} from 'miniprogram-api-promise';
import {
setCache
} from './cache'
import BaseModel from "../models/base"
const base = new BaseModel()
import RequestCode from "../models/request/requestCode.js"
/**
* @description promise化小程序api接口
* @returns {object} promise化后api集合
*/
const wxp = {}
// promisify all wx's api
promisifyAll(wx, wxp)
export {
wxp
}
//使用
globalData: {
//全局数据管理
wxp: {}, //全局微信api-Promise化管理器
userInfo: {},
hasLogin: false,
to
},
async checkSession() {
const [sessionErrMsg, sessionOK] = await to(this.globalData.wxp.checkSession());
//挂在于全局变量中
const sessionErrMsg = await this.globalData.wxp.checkSession();
this.globalData.hasLogin = true;
},
错误处理
在使用 async...await 方法时,经常采用 try...catch 捕获异常,如果有多个异步操作,需要每一次书写 try...catch。这样代码的简洁性较差,为了使代码更加的优雅,我们通过使用 await-to-js 库来处理异常。详细使用参考这里
const [sessionErrMsg, sessionOK] = await to(this.globalData.wxp.checkSession());
//如果存在sessionOK则正常执行