1.首先在until文件中创建common.js文件(根据你自己的实际情况定,重点在下边的函数封装中)
// 复制信息
export function copyData (data) {uni.setClipboardData({data: data,success: function () {uni.showToast({title: '复制成功'})}});
}// 保存图片
export function saveImage (image){// #ifdef MP// 获取用户的当前设置uni.getSetting({success: (res) => {if (res.authSetting['scope.writePhotosAlbum']) { // 验证用户是否授权可以访问相册handleDownload(image);} else {uni.authorize({ // 如果没有授权,向用户发起请求scope: 'scope.writePhotosAlbum',success: () => {handleDownload(image);},fail: () => {uni.showModal({content: '由于您还没有允许保存图片到您相册里,无法进行保存,请点击确定允许授权',success: (res) => {if (res.confirm) {uni.openSetting({success: (result) => {console.log(result.authSetting);}});}}});}})}}})// #endif// #ifdef APP-PLUShandleDownload(image);// #endif// #ifdef H5// 判断是否H5微信环境,true为微信浏览器const ua = navigator.userAgent.toLowerCase()if (ua.match(/MicroMessenger/i) == 'micromessenger') {vm.$u.toast('长按二维码保存');return;}uni.hideLoading();const oA = document.createElement("a");oA.download = new Date().getTime(); // 设置下载的文件名,默认是'下载'oA.href = image; // 临时路径再保存到本地document.body.appendChild(oA);oA.click();oA.remove(); // 下载之后把创建的元素删除uni.showToast({title: '保存成功',});// #endif
}// 下载图片
export function handleDownload (url){uni.getImageInfo({src: url,success: res => {uni.saveImageToPhotosAlbum({filePath: res.path,success: function () {uni.showToast({title: '保存成功',duration: 2000})},fail: async function () {// #ifdef APP-PLUSconst systemInfo = uni.getSystemInfoSync();if (systemInfo.platform == 'android') {let storage = await permission.requestAndroidPermission('android.permission.WRITE_EXTERNAL_STORAGE');if (storage == 0 || storage == -1) {toAppPermissionSetting('需要开启相册使用权限');return;}} else {let photoLibrary = permission.judgeIosPermission("photoLibrary"); // 判断ios是否给予相册权限if (!photoLibrary) {toAppPermissionSetting('需要开启相册使用权限');}}// #endifuni.showToast({title: '保存失败',duration: 2000})}})}})
}
2,上述代码就是封装的功能函数,需要用的时候在页面组件中引入该函数,然后methods中直接使用
3.方法很简单具体,如果对大家有帮助麻烦点亮小红星啦,感谢各位大佬。