平时开发一些小代码段,希望对新手有一些帮助。有问题也请大家指导一下
发布于 4 年前 作者 wei05 1245 次浏览 来自 分享

小程序开发一段时间了,从小白慢慢走到熟练使用。从当初看文档查资料,一步步走来。总结了一些小代码段,希望对新手有一些帮助,如果有问题也可以一起讨论。

1.小程序API API Promise化

这点感谢老张,的确现在API接口原生支持Promise化

这个作为第一点,我是觉得特别的重要的。如果不了解promise,请自行百度一下,认真地了解与理解。这个对以后开发小程序非常地重要。特别是当使用

wx.login wx.getUserInfo 同时调用,或是关联获取相同信息内容时。如果没有使用promise化API接口,很容易在回调在迷失了。

像以下代码,要success连续有其它操作,整段代码非常不易于阅读

getuserinfo:function (){
 //登陆
 wx.login({
  success:function (res){
   let code = res.code;
   //获取使用信息
   wx.getUserInfo({
    withCredentials:true,
    lang:'zh_CN',
    success:function(res){
     //与后端接口通讯
     wx.request({
      url : '',
      data : ,
      header : ''
      method : 'GET',
      dataType : 'json',
      responseType : 'text',
      success:function(res){
       //通讯成功返回操作
      }
     })
    }
   })
  }
 });
}

如果API使用promise化为,代码如下,整体比较易于阅读。需要阅读的习惯就是JS代码一行行执行下去

getuserinfo:async function (){
 try {
  //登陆
   let login = await wx.login();//code
  if(login.code){
   //获取用户数据
    let userinfo = await wx.getUserInfo({
     withCredentials : true,
     lang : 'zh_CN'
    });
    //与后端通讯
    let res = await wx.request({
     url : '',
     data : {code : login.code, userinfo : userinfo},
     header : ''
     method : 'GET',
     dataType : 'json',
     responseType : 'text'
    });
    if(res.errCode){
     console.log(res)
    }else{
     console.log()
    }
  }
 }catch (e) {
  //出错
  console.log(e);
 }
}

2.页面公共方法

在开发过程可能会大量使用到一些方法 如跳转,页面重新加载(刷新)。。。这些比较多的api,我一般都把些方法写一个通用接口中

wx.navigateTo

module.exprots = { page_init : page_init }
function page_init(page){
  tap_nav(page);
}
//page为当前页面 this
function tap_nav(page){
  //获取当前页面栈,用于判断是否已经到达数量
  let history = getCurrentPages();
  page.tap_nav = function (e){
   //获取链接地址
   let url = e.currentTarget.dataset.url;
   //判断当前页面栈是否大于或等于9,这里不可以是10
   if(history.length >= 9){
   //如果是大于或等于9,则现在替换页面记录跳转
    wx.redirectTo({
     url : url
    })
  }else{
  //正常现在跳转链接
   wx.navigateTo({
    url: url
   })
  }
 }
}

js调用
const page_tools = require('');
Page({
  onLoad : function(){
    let that = this;
    page_tools.page_init(thst);
  }
})

wxml如下
跳转
使用其它元素也可以 button image
2 回复

3.小程序全局数据

在小程序的,有时会有一些全局共用数据。比如用户信息或是其它一些配置信息。

一般都是使用app.globalData 或是 缓存,设置一下过期时间,达到过期时间后,再重新获取一下数据。但缓存有时会出现一些小问题,建议使用app.globalData。

App({
  globalData: {
    userInfo: null,
    config : null
  },
  onLaunch: function () {

  },
  page_load : async function (page){
    let that = this;
    let result = [];
    try {
      result['config'] = await that.load_config(page);
      return result;
    }catch (e) {
     console.log(e);
     return false;
    }
  },
  load_config : async function (page){
    let that = this;
    //当前时间戳
    let time = new Date().getTime();
    try {
      //读取数据
      let config = that.globalData.config || false;
      //如果数据存在,且过期时间大于当前时间
      if(config && config.exit_time >= time){
        //把数据setData到页面
       page.setData({
         config : config
       })
        //返回获取到的数据
        return config;
      }else{
        //数据不存在或是过期时间小于当前时间,重新通过接口获取数据
       let res = await wx.request({
        url : '',
        data : {},
        header : '',
        method : 'GET',
        dataType : 'json',
        responseType : 'text'
       });
       config = res.data.config;
       //配置过期时间
       config['exit_time'] = time + 7200 * 1000;
        //把数据setData到页面
       page.setData({
         config : config
       })
        //数据写入到globalData
        that.globalData.config = config;
        //返回获取到的数据
       return config;
      }
    }catch (e) {
     console.log(e);
     return false;
    }
  },
})

页面调用

const app = getApp();

Page({
  //页面的初始数据
  data: {},
  //*生命周期函数--监听页面加载
  onLoad:async function (options) {
  let that = this;
  try{
   let page_load = await app.page_load(that);
   console.log(page_load);
    }catch (e){
   console.log(e);
   return false;
    }
  }
})

1、大部分原生的wx.xxx函数已经原生支持promise了,可直接用了。比如let res = await wx.showModal()

2、wx.navigateTo这么用,显然是用力过猛了。

回到顶部