This is the 14th day of my participation in Gwen Challenge

The usual business is Vue+ Element background system, the common code List to share with you, welcome to correct ~

Base64 converts to Blob

// Convert Base64 to 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 });
}
Copy the code

Network image to Blob

// Convert web urls to bloBs
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(); }); }Copy the code

Get MIME in Base64

// Get the base64 file type
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;
}
Copy the code

Download the image from image Src

/ / blob downloaded
export async function downFile(url, fileName = "download") {
  try {
    let blob = null;
    // Local image network image base64 image processing
    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); }}Copy the code

Automatic registration of official global components

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)
})
Copy the code

File size and type validation

// Verify file size
export function fileSizeValidate(size, num) {
  if (size / 1024 / 1024 > num) {
    this.$message.info('The uploaded file shall not be greater than${num}MB`)
    return false
  } else {
    return true}}// File type validation
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}}Copy the code

Global filter quick Settings

// Global filter main.js
import * as glofilter from '@/filters' // Global filter
Object.keys(glofilter).forEach(item= > Vue.filter(item, glofilter[item]))
Copy the code

Format file size

// Format the file size
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) // The number of decimal places reserved
  return size + unitArr[index]
}
Copy the code

Base64 stitching

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

Text link replication

copyPersonURL(content) {
    let that = this
    if (window.ClipboardData) {
        window.clipboardData.setData('text', content)
        this.$message.success('Link copied successfully')}else {
        ;(function (content) {
            document.oncopy = function (e) {
                e.clipboardData.setData('text', content)
                e.preventDefault()
                document.oncopy = null
                that.$message.success('Link copied successfully')
            }
        })(content)
        document.execCommand('Copy')}},Copy the code

Timestamp conversion time

// Timestamp to year, month, day, minute, second
export const Time = value= > {
  return transformTime(value)
}
function transformTime(timestamp = +new Date(a)) {
  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 + The '-' + addZero(M) + The '-' + addZero(d) + ' ' + addZero(h) + ':' + addZero(m) + ':' + addZero(s)
  } else {
    return ' '}}function addZero(m) {
  return m < 10 ? '0' + m : m
}
Copy the code

Character length filter

// Character length filter
export const lengthTooLang = (value, length) = > {
    if (value.length > length) {
        return value.substr(0, length) + '... '
    }
    return value
}
Copy the code

Global scrollbar

::-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;
}
Copy the code

Tip element – confirm

this.$confirm('This operation will permanently delete the file. Do you want to continue? '.'tip', {
        confirmButtonText: 'sure'.cancelButtonText: 'cancel'.type: 'warning'
    }).then(() = > {
        this.$message({
            type: 'success'.message: 'Deleted successfully! '
        });
    }).catch(() = > {
        this.$message({
            type: 'info'.message: 'Cancelled delete'
        });          
});
Copy the code

Confirm prompt Promise version

// Confirm prompt
    areYouOK(tips) {
      return new Promise((resolve, reject) = > {
        this.$confirm(tips ? tips : 'Are you sure you're setting it as the default package? '.'tip', {
          confirmButtonText: 'sure'.cancelButtonText: 'cancel'.type: 'warning'
        })
          .then(() = > {
            resolve()
          })
          .catch(() = > {
            this.$message({
              type: 'info'.message: 'Cancelled operation'
            })
            reject('Operation cancel')})})}/ / use
async use() {
  try {
    await this.areYouOK('ha ha')... }catch (error) {
    console.log(error)
  }
}
Copy the code

Capitalize the first letter

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

Data type validation

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)];
}
Copy the code