Oct1a

前端常用代码片段

平常做的业务都是 Vue+element 的后台系统, 把自己常用的代码List分享给大家, 欢迎指正~

base64转换为Blob

// 将base64转为blob
export function dataURLtoBlob(base64, mimeType = "image/png") {
  let bytes = window.atob(base64.split(",")[1]);
  let ab = new ArrayBuffer(bytes.length);
  let ia = new Uint8Array(ab);
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeType });
}

网络图片转为Blob

// 将网络url转为blob
export function getBlob(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = () => {
      if (xhr.status == 200) {
        resolve(xhr.response);
      } else {
        reject();
      }
    };
    xhr.send();
  });
}

Base64中获取MIME

// 获取base64文件类型
export function getBase64Type(base64) {
  let index0 = base64.indexOf(":");
  let index1 = base64.indexOf(";");
  let mime = "";
  if (index0 !== -1 && index1 !== -1) {
    mime = base64.slice(index0 + 1, index1);
  }
  return mime;
}

通过图片Src下载图片

// blob下载
export async function downFile(url, fileName = "download") {
  try {
    let blob = null;
    // 本地图片 网络图片 base64图片处理
    if (url.startsWith("http")) {
      blob = await getBlob(url);
    } else if (url.startsWith("data:image")) {
      let mime = getBase64Type(url);
      blob = mime ? dataURLtoBlob(url, mime) : dataURLtoBlob(url);
    } else if (url.startsWith("/")) {
      blob = await getBlob(window.origin + url);
    } else {
      return;
    }

    let a = document.createElement("a");
    a.download = fileName;
    a.href = window.URL.createObjectURL(blob);
    a.click();
  } catch (error) {
    console.log(error);
  }
}

官方全局组件自动注册

var requireComponent = require.context("./src", true, /Base[A-Z]\w+\.(vue|js)$/)
requireComponent.keys().forEach(function (fileName) {
  var baseComponentConfig = requireComponent(fileName)
  baseComponentConfig = baseComponentConfig.default || baseComponentConfig
  var baseComponentName = baseComponentConfig.name || (
    fileName
      .replace(/^.+\//, '')
      .replace(/\.\w+$/, '')
  )
  Vue.component(baseComponentName, baseComponentConfig)
})

文件大小与类型验证

// 文件大小验证
export function fileSizeValidate(size, num) {
  if (size / 1024 / 1024 > num) {
    this.$message.info(`上传文件不得大于${num}MB`)
    return false
  } else {
    return true
  }
}
// 文件类型验证
export function validFileType(file) {
  if (!file.type) {
    return false
  }
  /**
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/pdf',
    'image/jpeg',
    'image/png',
    'application/zip',
    'application/x-rar-compressed',
    'application/x-zip-compressed',
   */
  const fileTypes = ['application/vnd.android.package-archive', 'application/iphone']
  if (fileTypes.includes(file.type)) {
    return true
  } else {
    return false
  }
}

全局过滤器快捷设置

// 全局过滤器 main.js
import * as glofilter from '@/filters' // 全局过滤器
Object.keys(glofilter).forEach(item => Vue.filter(item, glofilter[item]))

格式化文件大小

//格式化文件大小
export const renderSize = value => {
  if (null == value || value == '') {
    return '0 Bytes'
  }
  var unitArr = new Array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
  var index = 0
  var srcsize = parseFloat(value)
  index = Math.floor(Math.log(srcsize) / Math.log(1024))
  var size = srcsize / Math.pow(1024, index)
  size = size.toFixed(2) //保留的小数位数
  return size + unitArr[index]
}

base64拼接

<template slot-scope="scope">
          <div class="imgBox">
            <img :src="'data:img/jpg;base64,' + scope.row.fileBase64" alt />
          </div>
</template>

文本链接复制

copyPersonURL(content) {
    let that = this
    if (window.ClipboardData) {
        window.clipboardData.setData('text', content)
        this.$message.success('链接复制成功')
    } else {
        ;(function (content) {
            document.oncopy = function (e) {
                e.clipboardData.setData('text', content)
                e.preventDefault()
                document.oncopy = null
                that.$message.success('链接复制成功')
            }
        })(content)
        document.execCommand('Copy')
    }
},

时间戳转换时间

// 时间戳转年月日 时分秒
export const Time = value => {
  return transformTime(value)
}
function transformTime(timestamp = +new Date()) {
  if (timestamp) {
    var time = new Date(timestamp)
    var y = time.getFullYear()
    var M = time.getMonth() + 1
    var d = time.getDate()
    var h = time.getHours()
    var m = time.getMinutes()
    var s = time.getSeconds()
    return y + '-' + addZero(M) + '-' + addZero(d) + ' ' + addZero(h) + ':' + addZero(m) + ':' + addZero(s)
  } else {
    return ''
  }
}
function addZero(m) {
  return m < 10 ? '0' + m : m
}

字符长度过滤器

// 字符长度过滤器
export const lengthTooLang = (value, length) => {
    if (value.length > length) {
        return value.substr(0, length) + '...'
    }
    return value
}

全局滚动条

::-webkit-scrollbar {
  width: 7px;
  height: 5px;
  border-radius:15px;
  -webkit-border-radius:  15px;
}
::-webkit-scrollbar-track-piece {
  background-color: #fff;
  border-radius:15px;
  -webkit-border-radius:  15px;
}
::-webkit-scrollbar-thumb:vertical {
  height: 5px;
  background-color: rgba(144, 147, 153, 0.5);
  border-radius: 15px;
  -webkit-border-radius:  15px;
}
::-webkit-scrollbar-thumb:horizontal {
  width: 7px;
  background-color: rgba(144, 147, 153, 0.5);
  border-radius:  15px;
  -webkit-border-radius: 15px;
}

element-confirm提示

this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        this.$message({
            type: 'success',
            message: '删除成功!'
        });
    }).catch(() => {
        this.$message({
            type: 'info',
            message: '已取消删除'
        });
});

confirm提示Promise版

// 确认提示
    areYouOK(tips) {
      return new Promise((resolve, reject) => {
        this.$confirm(tips ? tips : '确认设置为默认包?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            resolve()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
            reject('操作取消')
          })
      })
    }

//使用
async use() {
  try {
    await this.areYouOK('哈哈')
    ...
  } catch (error) {
    console.log(error)
  }
}

首字母转大写

let firstUpperCase = ([first, ...rest]) => first?.toUpperCase() + rest.join('')

数据类型验证

function typeOf(obj) {
  const toString = Object.prototype.toString;
  const map = {
    '[object Boolean]'  : 'boolean',
    '[object Number]'   : 'number',
    '[object String]'   : 'string',
    '[object Function]' : 'function',
    '[object Array]'    : 'array',
    '[object Date]'     : 'date',
    '[object RegExp]'   : 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]'     : 'null',
    '[object Object]'   : 'object',
    '[object FormData]' : 'formData'
  };
  return map[toString.call(obj)];
}

JS判断浏览器是微信还是支付宝

function WxOrAli(){
    var ua = window.navigator.userAgent.toLowerCase();
    //判断是不是微信
    if ( ua.match(/MicroMessenger/i) == 'micromessenger' ) {
        return "WeiXIN";
    }
    //判断是不是支付宝
    if (ua.match(/AlipayClient/i) == 'alipayclient') {
        return "Alipay";
    }
    //哪个都不是
    return "false";
}
//写cookies函数
function SetCookie(name, value)//两个参数,一个是cookie的名子,一个是值
{
    var Days = 30; //此 cookie 将被保存 30 天
    var exp = new Date(); //new Date("December 31, 9998");
    exp.setTime(exp.getTime() + Days
            * 1000);
    document.cookie = name + "=" + escape(value)+ ";expires=" + exp.toGMTString();
}
function getCookie(name)//取cookies函数
{
    var arr = document.cookie.match(new RegExp("(^| )"+ name + "=([^;]*)(;|$)"));
    if (arr != null)
        return unescape(arr[2]);
    return "";

}
function delCookie(name)//删除cookie
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval+ ";expires=" + exp.toGMTString();
}

本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。