Vue常用方法封装,全局导入

新建一个****.js文件

export default {
	// 数组去重
	arrUnique: function(arr) {
		return [...new Set(arr)]
	},

	/**
	 * 数组对象去重
	 * 
	 * @param {arrObj} 数组对象
	 */
	arrObjUnique: function(arrObj) {
		var hash = {};
		arrObj = arrObj.reduce(function(item, next) {
			hash[next.name] ? '' : hash[next.name] = true && item.push(next);
			return item
		}, [])
		console.log(arrObj);
		return arrObj
	},

	/**
	 * 数组排序,{type} 1:从小到大 2:从大到小 3:随机
	 * 
	 * @param {arrObj} 数组对象
	 */
	sort(arr, type = 1) {
		return arr.sort((a, b) => {
			switch (type) {
				case 1:
					return a - b;
				case 2:
					return b - a;
				case 3:
					return Math.random() - 0.5;
				default:
					return arr;
			}
		})
	},

	/**
	 * 格式化时间
	 * 
	 * @param  {time} 时间
	 * @param  {cFormat} 格式
	 * @return {String} 字符串
	 *
	 * @example formatTime('2018-1-29', '{y}/{m}/{d} {h}:{i}:{s}') // -> 2018/01/29 00:00:00
	 */
	export function parseTime(time, cFormat) {
	  if (arguments.length === 0 || !time) {
	    return null
	  }
	  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	  let date
	  if (typeof time === 'object') {
	    date = time
	  } else {
	    if ((typeof time === 'string')) {
	      if ((/^[0-9]+$/.test(time))) {
	        // support "1548221490638"
	        time = parseInt(time)
	      } else {
	        // support safari
	        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
	        // time = time.replace(new RegExp(/-/gm), '/')
	        time = time.slice(0,19).replace(new RegExp(/-/gm), '/').replace(new RegExp(/T/igm), ' ')
	      }
	    }
	
	    if ((typeof time === 'number') && (time.toString().length === 10)) {
	      time = time * 1000
	    }
	    date = new Date(time)
	  }
	  const formatObj = {
	    y: date.getFullYear(),
	    m: date.getMonth() + 1,
	    d: date.getDate(),
	    h: date.getHours(),
	    i: date.getMinutes(),
	    s: date.getSeconds(),
	    a: date.getDay()
	  }
	  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
	    const value = formatObj[key]
	    // Note: getDay() returns 0 on Sunday
	    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
	    return value.toString().padStart(2, '0')
	  })
	  return time_str
	}

	// 去除空格,type: 1-所有空格 2-前后空格 3-前空格 4-后空格
	trim(str, type) {
		type = type || 1
		switch (type) {
			case 1:
				return str.replace(/\s+/g, "");
			case 2:
				return str.replace(/(^\s*)|(\s*$)/g, "");
			case 3:
				return str.replace(/(^\s*)/g, "");
			case 4:
				return str.replace(/(\s*$)/g, "");
			default:
				return str;
		}
	},

	/**
	 * 手机号隐藏中间四位
	 * 
	 * @param phone
	 */
	phoneHideMidFour(phone) {
		var newPhone = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
		return newPhone;
	},

	/**
	 * 显示尾号四位
	 * 
	 * @param phone
	 */
	phoneShowTailFour(phone) {
		// var newPhone = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
		return phone.slice(-4).padStart(phone.length, '*');
	},



	/**
	 * 获取url参数
	 * 
	 * @param name
	 */
	getUrlParam(name) {
		let reg = new RegExp('(^|&?)' + name + '=([^&]*)(&|$)', 'i')
		let r = window.location.href.substr(1).match(reg)
		if (r != null) {
			return decodeURI(r[2])
		}
		return undefined
	},

	// function GetQueryString(name) {undefined
	//     var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	//     var r = window.location.search.substr(1).match(reg);
	//     if (r != null) return unescape(r[2]); return null;
	// }

	/**
	 * 生成随机数范围
	 * 
	 * @param min
	 * @param max
	 */
	random(min, max) { // 生成随机数范围  
		if (arguments.length === 2) {
			return Math.floor(min + Math.random() * ((max + 1) - min))
		} else {
			return null
		}
	},

	/**
	 * 过滤html代码(把<>转换)
	 * 
	 */
	filterTag(str) {
		str = str.replace(/&/ig, "&amp;");
		str = str.replace(/</ig, "&lt;");
		str = str.replace(/>/ig, "&gt;");
		str = str.replace(" ", " ");
		return str;
	},

	/**
	 * 判断类型集合
	 * 
	 */
	checkStr(str, type) {
		switch (type) {
			case 'phone': //手机号码
				return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
			case 'tel': //座机
				return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
			case 'card': //身份证
				return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
			case 'pwd': //密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线
				return /^[a-zA-Z]\w{5,17}$/.test(str)
			case 'postal': //邮政编码
				return /[1-9]\d{5}(?!\d)/.test(str);
			case 'QQ': //QQ号
				return /^[1-9][0-9]{4,9}$/.test(str);
			case 'email': //邮箱
				return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
			case 'money': //金额(小数点2位)
				return /^\d*(?:\.\d{0,2})?$/.test(str);
			case 'URL': //网址
				return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
			case 'IP': //IP
				return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
			case 'date': //日期时间
				return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) ||
					/^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
			case 'number': //数字
				return /^[0-9]$/.test(str);
			case 'english': //英文
				return /^[a-zA-Z]+$/.test(str);
			case 'chinese': //中文
				return /^[\\u4E00-\\u9FA5]+$/.test(str);
			case 'lower': //小写
				return /^[a-z]+$/.test(str);
			case 'upper': //大写
				return /^[A-Z]+$/.test(str);
			case 'HTML': //HTML标记
				return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
			default:
				return true;
		}
	},

	// 返回数据类型
	type(para) {
		return Object.prototype.toString.call(para).replace(/^\[object (\S+)\]$/, '$1')
	},

}

全局引用
main.js

import utils from './utils/libs/****.js'
Vue.prototype.$utils = utils

使用

this.$utils.functionName()

其他方法

// // 判断对象数组是否含有某个属性
// // 1. 常规解法
// arr.filter(item => item['key'] === 'yourValue').length !== 0
// // 2. 黑科技
// JSON.stringify(arr).indexOf('"type":2') !== -1

// // 深拷贝
// // 1. json暴力转化
// JSON.parse(JSON.stringify(obj))
// // 2. es6解构赋
// var obj2 = {...obj}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值