uniapp常用API—记着下次可能用得着

2022年9月14日 372点热度 0人点赞 0条评论










点击卡片进入小程序



今日福利>>



优惠券合集>>



最火壁纸合集>>

uniapp常用API---记着下次可能用得着

一、uniapp防抖节流的使用

节流

规定时间内,只触发一次,可以通过设置immediate来决定触发的时机在这个时间的开始,还是结束的时候执行。

// 此处用法为在js中调用,需要写this.$u.throttle()this.$u.throttle(this.toNext, 500)

防抖

使用uview 防止触发多次接口建议使用防抖

// 此处用法为在js中调用,需要写this.$u.debounce()this.$u.debounce(this.toNext, 500)

用当前点击时间为判断条件

data() {    return {        lasttime:""    };},methods:{    upload(){            let d = new Date();            let nowtime = d.getTime();//获取点击时间            if(nowtime - this.lasttime < 2000){ //如果两次点击事件间隔小于2秒,则不触发后面的接口。                return;            };            this.lasttime = nowtime;    }}

二、uniapp获取设备的ip和Mac----仅支持安卓

获取Ip地址

getDeviceIp(){                             var deviceIp = ‘’                  if(plus.os.name=="Android"){                      var Context = plus.android.importClass("android.content.Context");                      var wifiManager =plus.android.runtimeMainActivity().getSystemService(Context.WIFI_SERVICE);                      var wifiInfo = plus.android.invoke(wifiManager, "getConnectionInfo");                      var ipAddress = plus.android.invoke(wifiInfo, "getIpAddress");                      deviceIp = '';                      if (ipAddress != 0) {                          deviceIp = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));                      }                  }                  console.log(deviceIp)              return deviceIp;              },

获取mac地址

 getDeviceMac(){                                  var deviceMac = ‘’                  var net = plus.android.importClass("java.net.NetworkInterface")                  var wl0 = net.getByName('wlan0')                  var macByte = wl0.getHardwareAddress()                  deviceMac = ''                  for (var i = 0; i < macByte.length; i++) {                      var tmp = "";                      var num = macByte[i];                      if (num < 0) {                          tmp = (255 + num + 1).toString(16);                      } else {                          tmp = num.toString(16);                      }                      if (tmp.length == 1) {                          tmp = "0" + tmp;                      }                      deviceMac += tmp;                  }                  console.log(deviceMac)              },

三、自动更新(获取版本)

1、客户端检查手机型号

getUpdate() {            let that = this;            uni.getSystemInfo({                success: res => {                    console.log(res.platform);                    //检测当前平台,如果是安卓则启动安卓更新                    if (res.platform == 'android') {                        that.AndroidCheckUpdate();                    }                }            });        },

2、检查版本更新差异

2.1简单版

AndroidCheckUpdate: function() {            //检查是否更新            var that = this;            console.log(this.xBanben)            var currentVersion = plus.runtime.version; //获取当前app版本号            console.log(currentVersion);            this.banben = currentVersion;            if (currentVersion < this.xBanben) {                this.Update = true;            }        },

2.2复杂版

AndroidCheckUpdate() {  let that = this;  plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {    that.version = wgtinfo.version //客户端版本号    console.log('当前app版本信息:' + that.version);  })  that.getUpdateVersion()},getUpdateVersion() {  let that = this;  // 获取当前app版本信息  that.$req.get("/appUpdate/queryUpdate", {  }, {}).then(function (res) {    console.log('res.data:' + JSON.stringify(res.data))    console.log("现在的版本"+ that.version +"数据库版本"+ res.data.data.version +"进入查找app版本");    if(res.data.data.version>that.version){      // 这里下载apkurl从/appUpdate/queryUpdate接口请求返回数据中获取      that.downloadUrl = BaseUrl + '/' + res.data.data.androidUrl      // 是否强制更新(0 否;1 是)      that.isForceUpdate = res.data.data.isForceUpdate      uni.showModal({        // 更新提醒        title: '发现新版本,是否更新',        content: '此版本号:'+ that.version + '\xa0\xa0\xa0' + '待更新版本号:' + res.data.data.version,        success: res => {          if (res.confirm) {            that.downWgt();//下载文件            // that.showdownLine = true;            // plus.runtime.openURL(androidUrl)          } else if (res.cancel) {            console.log('that.isForceUpdate:' + that.isForceUpdate);            // 不更新强制退出app            if (that.isForceUpdate == 1) {              console.log('that.isForceUpdate1:' + that.isForceUpdate);              uni.showModal({                // 更新提醒                title: '发现新版本,是否更新',                content: '此版本为强制更新版本如不升级将退出APP',                success: res => {                  if (res.confirm) {                    console.log('不更新强制退出app');                    plus.runtime.quit();                  } else if (res.cancel) {                    that.AndroidCheckUpdate();                  }                }              });            }          }        }      });      //dtask.start();      }  }).catch(error => {    uni.showToast({      title: '调用请求失败',        mask: false,        duration: 5000,        icon:"none"      });    });  complete: () => {}  },

3.创建下载

版本1

// 创建下载任务        createDownload(url) {            var dtask = plus.downloader.createDownload(url, {}, function(d, status) {                // 下载完成                console.log(status);                if (status == 200) {                    console.log('Download success: ' + d.filename);                    plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, e => e, function(error) {                    });                    //只更新不首次安装                    // plus.runtime.install(                    //  data.tempFilePath,                    //  {                    //      force: false                    //  },                    //  function() {                    //      plus.runtime.restart();                    //  }                    // );                } else {                    console.log('Download failed: ' + status);                }            });            dtask.addEventListener('statechanged', task => {                if (task.state == 3) {                    let progress = (dtask.downloadedSize / dtask.totalSize) * 100;                    this.progress = Math.trunc(progress);                    // console.log(this.progress)                    if (progress >= 100) {                        this.Prompts = false;                    }                }            });            dtask.start();        },

版本2

downWgt() {  let that=this;  console.log('url:' + that.downloadUrl)  uni.showLoading({    title: '更新中……'  })
const downloadTask = uni.downloadFile({//执行下载 url: that.downloadUrl, //下载地址 timeout: 1000 * 30, //30秒超时时间 success: downloadResult => {//下载成功 that.showdownLine = false uni.hideLoading(); console.log('downloadResult.statusCode' + downloadResult.statusCode) if (downloadResult.statusCode == 200) { console.log('更新中') uni.showModal({ title: '', content: '更新成功,确定现在重启吗?', confirmText: '重启', confirmColor: '#EE8F57', success: function(res) { if (res.confirm == true) { plus.runtime.install(//安装 downloadResult.tempFilePath, { force: true }, function(res) { utils.showToast('更新成功,重启中'); plus.runtime.restart(); } ); } } }); } }, fail: err => { uni.hideLoading(); that.showdownLine = false that.$u.toast(err.errMsg) console.log(err) }, complete: com => { console.log(com) } });
// 下载进度 downloadTask.onProgressUpdate(res => { // that.$u.toast(res.progress) that.downloadNum = res.progress console.log('下载进度' + that.downloadNum); // console.log('已经下载的数据长度' + res.totalBytesWritten); // console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
// 满足测试条件,取消下载任务。 // if (res.progress > 50) { // downloadTask.abort(); // } });},

拼多多官方优惠:

84500uniapp常用API—记着下次可能用得着

这个人很懒,什么都没留下

文章评论