小程序相關封裝
時間戳封裝
文件 encapsulation.js
module.exports = {
? ?timestampToTime:(timestamp, connector, type)=> {
? ? var date = new Date(timestamp);//時間戳為10位需*1000蜒车,時間戳為13位的話不需乘1000
? ? var Y = date.getFullYear() + connector;
? ? var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + connector;
? ? var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
? ? var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
? ? var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
? ? var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
? ? if (type == 'YMD') {
? ? ? return Y + M + D;
? ? } else {
? ? ? return Y + M + D + h + m + s;
? ? }
? },
}
文件 index.js
let enca = require('../../public/encapsulation.js')? ?//路徑自己改一下
onLoad:function(){
? ?console.log(enca.timestampToTime(1234567890123, '-', 'YMDhms'))
}
showToast 封裝
module.exports = {
? ? // 提示 交互
? showToast : (title,icon) => {
? ? wx.showToast({
? ? ? title: title,
? ? ? icon: icon,
? ? ? duration: 1500,
? ? ? mask: true
? ? });
? },
}
文件 index.js
let enca = require('../../public/encapsulation.js')? ?//路徑自己改一下
onLoad:function(){
?enca.showToast("你好","none")
}
請求封裝
const host = 'https://? ?;//這個是你們的接口域名
function promise(url, params, method) {
? ? // 添加請求加載等待
? ? wx.showLoading({
? ? ? title: '加載中...'
? ? })
? ? return new Promise((resolve, reject) => {
? ? ? ? wx.request({
? ? ? ? ? ? url: `${url}`,
? ? ? ? ? ? data: params,
? ? ? ? ? ? method: method,
? ? ? ? ? ? header: {
? ? ? ? ? ? ? ? 'content-type':'application/x-www-form-urlencoded'? ?//請求頭
? ? ? ? ? ? },
? ? ? ? ? complete: (res) => {
? ? ? ? ? ? // 關閉等待動畫
? ? ? ? ? ? wx.hideLoading()
? ? ? ? ? ? ? ? // 是否登錄失效
? ? ? ? ? ? ? ? if(res.data.state == 0 && res.data.code == 97){
? ? ? ? ? ? ? ? ? ? wx.showToast({
? ? ? ? ? ? ? ? ? ? ? ? title: '登錄失效,請重新登錄',
? ? ? ? ? ? ? ? ? ? ? ? icon: "none",
? ? ? ? ? ? ? ? ? ? ? ? duration: 1500,
? ? ? ? ? ? ? ? ? ? })
? ? ? ? ? ? ? ? ? ? setTimeout(function(){
? ? ? ? ? ? ? ? ? ? ? ? wx.reLaunch({
? ? ? ? ? ? ? ? ? ? ? ? ? ? url: '/pages/user/index/index',? //失效后要跳轉(zhuǎn)的頁面
? ? ? ? ? ? ? ? ? ? ? ? })
? ? ? ? ? ? ? ? ? ? },1500)
? ? ? ? ? ? ? ? ? ? return
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? resolve(res)
? ? ? ? ? ? },
? ? ? ? ? ? fail: reject
? ? ? ? })
? ? })
}
module.exports = {
? ? // 登錄
? ? login: function (params) {
? ? ? return promise(host + '/login', params, 'POST')
? ? ? ? ? ? .then(res => res.data)
? ? },
}
index.js
onLoad:function(){
? ? api.login({
? ? ? ? ? ? ?// 需要給后臺傳的參數(shù)
? ? ? ? ? ?sort: 2,??
? ? ? ? ? ? start_pos: 0,
? ? }).then(res => {
? ? ? console.log(res)
? ? })
? },