这是我参与更文挑战的第14天,活动详情查看:更文挑战
平常做的业务都是
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)];
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END