小程序接触了一段时间,整理下常用的写法, 便于阅读,有好的风格欢迎留言
- 用let声明变量,用const声明常量
let version = '1.0.0';
const weekday = 7;
- Page函数接受的键值参数
Page({
onLoad() {
//....
},
});
- 模块的编写以及引入,采用ES6的import...from...
//util文件
function log(msg) {
...
}
module.exports = {
log: log
};
//xx.js文件
import {log} from '../../utils/util';
log('Application initialized !!');
- js文件中的函数需要使用this.data中数据时候,先采用解构的方法获取特定数据后再进行其他逻辑操作
let {year, month, day} = this.data;
...
- 使用箭头函数(Arrow Function)避免回调中this指针的问题,避免多余的let _this = this;写法(箭头函数是不绑定作用域的,不会改变当前this的作用域)
onLoad() {
let _this = this;
wx.getSystemInfo({
success: (res) => {
_this.setData({windowHeight: res.windowHeight});
}
});
}
onLoad() {
wx.getSystemInfo({
success: (res) => {
this.setData({windowHeight: res.windowHeight});
}
});
}
- js文件中事件的函数命名
//wxml中事件绑定函数
bindXXX: function (e) {}
//页面跳转
gotoXXX: function (e) {}
//web请求
wXXX: function (e) {}
//页面数据校验,返回bool值,true表示校验正确,逻辑
- 校验数据函数,方法采用checkXXX,返回bool值,true表示校验正确
//函数定义
checkXXX: function (e) {}
//使用校验函数
createPacket: function () {
if (!this.checkXXX()) {
return
}
//正常业务逻辑
....
}
- 打印log
console.log('payInfo=', payInfo)
(持续添加中...)
网友评论