百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

uniapp开发必备:10个实用Utils方法全解析,熬夜也要学

bigegpt 2024-08-27 12:05 4 浏览

uniapp常用的utils方法包括删除数组中指定元素、验证手机号、手机号脱敏、检查文件后缀类型、保存视频文件、保存图片、时间转换、时间前面补0、视频分享和图片分享。

以下是这些方法的详细说明和使用案例:

1、删除数组中指定元素:

  • 方法名:removeElementFromArray
  • 参数:array(要操作的数组)
  • 参数:element(要删除的元素)
  • 返回值:删除指定元素后的新数组
  • 使用案例:
/** 删除数组中指定元素 */
export function removeElementFromArray(array, element) {
  return array.filter((item) => item !== element);
}
const array = [1, 2, 3, 4, 5];
const element = 3;
const newArray = removeElementFromArray(array, element);
console.log(newArray); // [1, 2, 4, 5]

2、验证手机号:

  • 方法名:validatePhoneNumber
  • 参数:phoneNumber(要验证的手机号)
  • 返回值:验证结果(true表示手机号格式正确,false表示手机号格式错误)
  • 使用案例:
/** 验证手机号 */
export function validatePhoneNumber(phoneNumber) {
  const phonePattern = /^1\d{10}$/
  return phonePattern.test(phoneNumber)
}
const phoneNumber = '13812345678';
const isValid = validatePhoneNumber(phoneNumber);
console.log(isValid); // true

3、手机号脱敏:

  • 方法名:maskPhoneNumber
  • 参数:phoneNumber(要脱敏的手机号)
  • 返回值:脱敏后的手机号(前三位保留,中间用****替代,后四位保留)
  • 使用案例:
/** 手机号脱敏 */
export function maskPhoneNumber(phoneNumber) {
  if (!phoneNumber) {
    return ''
  }
  const maskedNumber = phoneNumber.substring(0, 3) + '****' + phoneNumber.substring(7);
  return maskedNumber;
}
const phoneNumber = '13812345678';
const maskedNumber = maskPhoneNumber(phoneNumber);
console.log(maskedNumber); // 138****5678

4、检查文件后缀类型:

  • 方法名:checkFileExtension
  • 参数:file(文件路径)
  • 返回值:文件类型(isVideo为true表示视频文件,isImg为true表示图片文件,否则为其他类型文件)
  • 使用案例:
/** 检查后缀类型 */
export function checkFileExtension(file) {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp'];
  const videoExtension = '.mp4';
  const fileExtension = file.substring(file.lastIndexOf('.')).toLowerCase();
  const isVideo = (fileExtension === videoExtension);
  const isImg = imageExtensions.some(ext => ext === fileExtension);
  return {
    isVideo,
    isImg,
  };
}
const file = 'test.jpg';
const fileType = checkFileExtension(file);
console.log(fileType); // {isVideo: false, isImg: true}

5、保存视频文件:

  • 方法名:downloadVideo
  • 参数:file(视频文件路径)
  • 功能:保存视频到手机相册
  • 使用案例:
/** 保存视频文件 */
export function downloadVideo(file) {
  uni.showLoading({
    title: '保存中...'
  });
  uni.authorize({
    /* scope.writePhotosAlbum 类型是保存到相册 */
    scope: 'scope.writePhotosAlbum',
    success() {
      uni.downloadFile({
        url: file,
        success: (res) => {
          uni.hideLoading()
          uni.saveVideoToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function() {
              showSuccessToast('视频保存成功');
            },
            fail: function() {
              showErrorToast('视频保存失败');
            }
          })
        },
      });
    }
  })
}
// 成功提示
export function showSuccessToast(message) {
  uni.showToast({
    title: message,
    icon: 'success',
    duration: 2000
  });
}
// 失败提示
export function showErrorToast(message) {
  uni.showToast({
    title: message,
    icon: 'error',
    duration: 2000
  });
}
const url = 'http://example.com/video.mp4';
shareVideo(url);

6、保存图片:

  • 方法名:downloadImage
  • 参数:file(图片路径)
  • 功能:保存图片到手机相册
  • 使用案例:
/** 保存图片 */
export function downloadImage(file) {
  uni.showLoading({
    title: '保存中...'
  });
  uni.authorize({
    /* scope.writePhotosAlbum 类型是保存到相册 */
    scope: 'scope.writePhotosAlbum',
    success() 
      uni.getImageInfo({
        src: file,
        success: function(image) {
          uni.hideLoading()
          uni.saveImageToPhotosAlbum({
            filePath: image.path,
            success: function() {
              showSuccessToast('图片保存成功');
            },
            fail(e) {
              showErrorToast('图片保存失败');
            }
          });
      	}
      });
    }
  })
}
const file = 'http://example.com/image.jpg';
downloadImage(file);

7、时间转换:

  • 方法名:convertSecondsToFormat
  • 参数:seconds(时间,单位为秒)
  • 返回值:转换后的时间格式(小时、分钟、秒钟)
  • 使用案例:
/** 时间转换 */
export function convertSecondsToFormat(seconds) {
  if (typeof time !== 'number' || time < 0) {
    return time
  }
  let hours = Math.floor((seconds % (24 * 60 * 60)) / (60 * 60));
  let minutes = Math.floor((seconds % (60 * 60)) / 60);
  let remainingSeconds = seconds % 60;
  return {
    hours: addZero(hours),
    minutes: addZero(minutes),
    seconds: addZero(remainingSeconds),
  };
}
/** 时间前面补0 */
export function addZero(value) {
  return value < 10 ? "0" + value : value;
}
const seconds = 3600;
const timeFormat = convertSecondsToFormat(seconds);
console.log(timeFormat); // {hours: '01', minutes: '00', seconds: '00'}

8、视频分享:

  • 方法名:shareVideo
  • 参数:url(视频地址)
  • 功能:下载视频并分享
  • 使用案例:
/** 视频分享 */
export function shareVideo(url) {
  wx.downloadFile({
    url: url, // 下载url
    success(res) {
      // 下载完成后转发
      wx.shareVideoMessage({
        videoPath: res.tempFilePath,
        success() {},
        fail: console.error,
      })
    },
    fail: console.error,
  })
}
const url = 'http://example.com/video.mp4';
shareVideo(url);

9、图片分享:

  • 方法名:shareImage
  • 参数:url(图片地址)
  • 功能:下载图片并分享
  • 使用案例:
/** 图片分享 */
export function shareImage(url) {
  wx.downloadFile({
    url: url,
    success: (res) => {
      wx.showShareImageMenu({
        path: res.tempFilePath,
        success() {},
        fail: console.error,
      })
    }
  })
}
const url = 'http://example.com/image.jpg';
shareImage(url);

如果喜欢,可以点赞收藏,关注哟~

相关推荐

Go语言泛型-泛型约束与实践(go1.7泛型)

来源:械说在Go语言中,Go泛型-泛型约束与实践部分主要探讨如何定义和使用泛型约束(Constraints),以及如何在实际开发中利用泛型进行更灵活的编程。以下是详细内容:一、什么是泛型约束?**泛型...

golang总结(golang实战教程)

基础部分Go语言有哪些优势?1简单易学:语法简洁,减少了代码的冗余。高效并发:内置强大的goroutine和channel,使并发编程更加高效且易于管理。内存管理:拥有自动垃圾回收机制,减少内...

Go 官宣:新版 Protobuf API(go pro版本)

原文作者:JoeTsai,DamienNeil和HerbieOng原文链接:https://blog.golang.org/a-new-go-api-for-protocol-buffer...

Golang开发的一些注意事项(一)(golang入门项目)

1.channel关闭后读的问题当channel关闭之后再去读取它,虽然不会引发panic,但会直接得到零值,而且ok的值为false。packagemainimport"...

golang 托盘菜单应用及打开系统默认浏览器

之前看到一个应用,用go语言编写,说是某某程序的windows图形化客户端,体验一下发现只是一个托盘,然后托盘菜单的控制面板功能直接打开本地浏览器访问程序启动的webserver网页完成gui相关功...

golang标准库每日一库之 io/ioutil

一、核心函数概览函数作用描述替代方案(Go1.16+)ioutil.ReadFile(filename)一次性读取整个文件内容(返回[]byte)os.ReadFileioutil.WriteFi...

文件类型更改器——GoLang 中的 CLI 工具

我是如何为一项琐碎的工作任务创建一个简单的工具的,你也可以上周我开始玩GoLang,它是一种由Google制作的类C编译语言,非常轻量和快速,事实上它经常在Techempower的基准测...

Go (Golang) 中的 Channels 简介(golang channel长度和容量)

这篇文章重点介绍Channels(通道)在Go中的工作方式,以及如何在代码中使用它们。在Go中,Channels是一种编程结构,它允许我们在代码的不同部分之间移动数据,通常来自不同的goro...

Golang引入泛型:Go将Interface「」替换为“Any”

现在Go将拥有泛型:Go将Interface{}替换为“Any”,这是一个类型别名:typeany=interface{}这会引入了泛型作好准备,实际上,带有泛型的Go1.18Beta...

一文带你看懂Golang最新特性(golang2.0特性)

作者:腾讯PCG代码委员会经过十余年的迭代,Go语言逐渐成为云计算时代主流的编程语言。下到云计算基础设施,上到微服务,越来越多的流行产品使用Go语言编写。可见其影响力已经非常强大。一、Go语言发展历史...

Go 每日一库之 java 转 go 遇到 Apollo?让 agollo 来平滑迁移

以下文章来源于GoOfficialBlog,作者GoOfficialBlogIntroductionagollo是Apollo的Golang客户端Apollo(阿波罗)是携程框架部门研...

Golang使用grpc详解(golang gcc)

gRPC是Google开源的一种高性能、跨语言的远程过程调用(RPC)框架,它使用ProtocolBuffers作为序列化工具,支持多种编程语言,如C++,Java,Python,Go等。gR...

Etcd服务注册与发现封装实现--golang

服务注册register.gopackageregisterimport("fmt""time"etcd3"github.com/cor...

Golang:将日志以Json格式输出到Kafka

在上一篇文章中我实现了一个支持Debug、Info、Error等多个级别的日志库,并将日志写到了磁盘文件中,代码比较简单,适合练手。有兴趣的可以通过这个链接前往:https://github.com/...

如何从 PHP 过渡到 Golang?(php转golang)

我是PHP开发者,转Go两个月了吧,记录一下使用Golang怎么一步步开发新项目。本着有坑填坑,有错改错的宗旨,从零开始,开始学习。因为我司没有专门的Golang大牛,所以我也只能一步步自己去...