小程序开发常用样式及代码
最近开发的小程序项目比较多,为了避免重复造轮子,在这里总结一些自己用到的常用代码
app.wxss
.container {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 200rpx 0;
box-sizing: border-box;
}
/* 背景色 */
.background{
background-color: #f0f0f0;
height: 100%;
}
/* 横着的分割View样式 */
/*分割线样式*/
.divline{
background: #E0E3DA;
width: 100%;
height: 1px;
}
/* 纵向分割线 */
.divline-v{
background-color: #a0a0a0;
width: 1px;
margin-left: 8rpx;
margin-right: 8rpx;
height: 32rpx;
}
/* 大号字体 */
.font-h1{
font-size: 39rpx;
}
/* 中号字体 */
.font-h2{
font-size: 32rpx;
}
/* 小号字体 */
.font-h3{
font-size: 28rpx;
}
/* 超小号字体 */
.font-h4{
font-size: 24rpx;
}
.bold{
font-weight: 600;
}
.padding-small{
height: 32rpx;
}
.padding-medium{
height: 64rpx;
}
.padding-big{
height: 128rpx;
}
.vlayout{
display: flex;
justify-content: start;
align-content: flex-start;
flex-direction: column;
text-align: start;
align-items: flex-start;
}
.hlayout{
display: flex;
flex-direction: row;
}
/* 底部按钮 */
.btn-bottom{
bottom:0;
background-color: #DB421E;
padding: 16rpx;
font-size: 32rpx;
width: 100vw;
color: white;
}
/* 指针经过 */
.btn-bottom:hover{
color:white;
}
/* 被按下 */
.btn-bottom:active{
color:white;
background-color: #e84925;
}
app.js
App({
url: "https://app.yzjlb.com/api/",
url_json: "https://www.yzjlb.net/app/",
url_img: "https://app.yzjlb.com/",
openid: wx.getStorageSync("openid"),
onLaunch: function() {
console.log("openid=",wx.getStorageSync("openid"));
if (!this.isLogin()){
console.log("openid为空")
}
},
globalData: {
userInfo: null,
code:null
},
/*获取当前页url*/
getCurrentPageUrl: function () {
var pages = getCurrentPages() //获取加载的页面
var currentPage = pages[pages.length - 1] //获取当前页面的对象
var url = currentPage.route //当前页面url
console.log("--> url " + url);
return url
},
//登陆服务器
login: function(code, avatar, nickname,onLogin=null) {
var that = this;
netUtil.getRequest(that.url + "login/login?" + "code=" + code +
"&nickname=" + decodeURIComponent(nickname)
+ "&avatar=" + decodeURIComponent(avatar), () => {
wx.showLoading({
title: '登陆中',
})
},
(res) => {
wx.hideLoading();
console.log(res);
if (res.code == 200) {
wx.setStorageSync("openid", res.data.openid);
that.openid = res.data.openid;
if(onLogin)
onLogin();
}
else{
util.showErrorToast(""+res.msg)
}
},
(res) => {
wx.hideLoading();
util.showErrorToast("登陆失败")
})
},
//检测是否已登陆
isLogin:function(){
var that = this;
if(that.openid){
return true;
}
return false;
},
/**
* json转字符串并格式化
*/
jsonToString: function(data) {
return this.formatJson(JSON.stringify(data));
},
/**
*字符串转json
*/
stringToJson: function(data) {
return JSON.parse(data);
},
//因为获取第二次信息会造成openid失效 所以加一个判断==========================================================================================
isFirstShare: function(code) {
if (wx.getStorageSync("code")) {
if (wx.getStorageSync("code") == code) {
return false;
} else {
wx.setStorageSync("code", code);
return true;
}
} else {
wx.setStorageSync("code", code);
return true;
}
},
formatJson: function(jsonStr) {
if (null == jsonStr || "" == jsonStr)
return "";
jsonStr = jsonStr.replace(" ", "");
jsonStr = jsonStr.replace("\t", "");
var sb = "";
var last = '\0';
var current = '\0';
var indent = 0;
var isInQuotationMarks = false;
for (var i = 0; i < jsonStr.length; i++) {
last = current;
current = jsonStr.charAt(i);
switch (current) {
case '"':
if (last != '\\') {
isInQuotationMarks = !isInQuotationMarks;
}
sb += (current);
break;
case '{':
case '[':
sb += (current);
if (!isInQuotationMarks) {
sb += ('\n');
indent++;
this.addIndentBlank(sb, indent);
}
break;
case '}':
case ']':
if (!isInQuotationMarks) {
sb += ('\n');
indent--;
this.addIndentBlank(sb, indent);
}
sb += (current);
break;
case ',':
sb += (current);
if (last != '\\' && !isInQuotationMarks) {
sb += ('\n');
this.addIndentBlank(sb, indent);
}
break;
case ' ':
break;
case '\n':
break;
default:
if (current != '\n')
sb += (current);
}
}
return sb.toString();
},
addIndentBlank: function(sb, indent) {
for (var i = 0; i < indent; i++) {
sb += (" ");
}
},
})
联网模块方法 NetUtil.js
/**
* 工具类使用方法
* const netUtil = require("../../utils/NetUtil.js");
*/
/**
* 供外部post请求调用
* @url 链接
* @params 参数
* @onStart 开始联网
* @onSuccess 联网成功
* @onFailed 联网失败
*/
function post(url, params, onStart, onSuccess, onFailed) {
request(url, params, "POST", onStart, onSuccess, onFailed);
}
/**
* 供外部get请求调用
* @url 链接
* @onStart 开始联网
* @onSuccess 联网成功
* @onFailed 联网失败
*/
function get(url, onStart, onSuccess, onFailed) {
request(url, null, "GET", onStart, onSuccess, onFailed);
}
/**
* function: 封装网络请求
* @url URL地址
* @params 请求参数
* @method 请求方式:GET/POST
* @onStart 开始请求,初始加载loading等处理
* @onSuccess 成功回调
* @onFailed 失败回调
*/
function request(url, params, method, onStart, onSuccess, onFailed) {
onStart(); //request start
wx.request({
url: url,
data: dealParams(params),
method: method,
header: { 'content-type': 'application/json' },
success: function (res) {
console.log(url,res.data);
if (res.data) {
/** start 根据需求 接口的返回状态码进行处理 */
if (res.data.code) {
console.log(url,res);
onSuccess(res.data); //request success
} else {
console.log("没有code参数")
onFailed(res.data); //request failed
}
/** end 处理结束*/
}
},
fail: function (error) {
console.log("加载错误:url",error);
onFailed(""); //failure for other reasons
}
})
}
/**
* function: 根据需求处理请求参数:添加固定参数配置等
* @params 请求参数
*/
function dealParams(params) {
return params;
}
module.exports = {
postRequest: post,
getRequest: get,
}
使用方法
1.在page中导入
const netUtil = require("../../utils/NetUtil.js");
2.调用get请求
var that = this;
netUtil.getRequest(app.url + "package/getPackages", () => {
util.showLoading();
},
(res) => {
console.log("获取成功", res)
if (res.code == 200) {
that.setData({
list: res.data
})
}
else {
util.showErrorToast("" + res.msg);
}
util.hideLoading();
},
(error) => {
util.showErrorToast("加载错误");
console.log("加载错误", error)
util.hideLoading();
});
常用工具方法util.js
注意,这个工具需要用到一张图片 /img/toast_error.png
/**
* 组件使用方法:const util = require("../../utils/util.js");
*/
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatDate2(time) {
// 获取年月日时分秒值 slice(-2)过滤掉大于10日期前面的0
var datetime = 0;
if (time instanceof String) {
datetime = parseInt(datetime);
}
else{
datetime = parseInt(time);
}
console.log(datetime)
var date = new Date(datetime*1000);
console.log(date);
var year = date.getFullYear();
// console.log(""+year);
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + date.getDate()).slice(-2);
var hour = ("0" + date.getHours()).slice(-2);
var minute = ("0" + date.getMinutes()).slice(-2);
var second = ("0" + date.getSeconds()).slice(-2);
// 拼接
var result = year + "年" + month + "月" + day + " " + hour + ":" + minute + ":" + second;
// 返回
return result;
}
//将毫秒的时间转换成美式英语的时间格式,eg:3rd May 2018
function formatDate(millinSeconds) {
if (millinSeconds instanceof String) {
millinSeconds = Integer.parseInt(millinSeconds);
}
console.log("" + millinSeconds)
var date = new Date(millinSeconds);
var monthArr = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Spt", "Oct", "Nov", "Dec");
var suffix = new Array("st", "nd", "rd", "th");
var year = date.getFullYear(); //年
var month = monthArr[date.getMonth()]; //月
var ddate = date.getDate(); //日
if (ddate % 10 < 1 || ddate % 10 > 3) {
ddate = ddate + suffix[3];
} else if (ddate % 10 == 1) {
ddate = ddate + suffix[0];
} else if (ddate % 10 == 2) {
ddate = ddate + suffix[1];
} else {
ddate = ddate + suffix[2];
}
console.log("" + month + " " + year)
return ddate + " " + month + " " + year;
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
//显示错误信息
const showErrorToast = (text) => {
wx.showToast({
image: "/img/toast_error.png",
title: text,
})
}
//显示一个简单的toast
const showToast = (text) => {
wx.showToast({
title: text,
})
}
//显示加载框
const showLoading = () => {
wx.showLoading({
title: '加载中',
})
}
//取消显示加载框
const hideLoading = () => {
wx.hideLoading();
}
//显示
module.exports = {
formatTime: formatTime,
formatDate: formatDate,
formatDate2: formatDate2,
showLoading: showLoading,
hideLoading: hideLoading,
showToast: showToast,
showErrorToast: showErrorToast
}