## Vue 项目中工具函数,我们通常会添加到Vue的原型中,这样就实现了全局函数

import Vue from 'vue'
Vue.prototype.$tools = function (){}复制代码

只需要将绑定的这段js引入到main.js即可。绑定方法十分简单,这里不再详细说明

下面列举几个常用的工具函数

# $dateFormat 事件格式化函数,相对于moment轻很多

Vue.prototype.$dateFormat = function (date, fmt = 'YYYY-MM-DD HH:mm:ss') {if (!date) {return ''}if (typeof date === 'string') {date = new Date(date.replace(/-/g, '/'))}if (typeof date === 'number') {date = new Date(date)}var o = {'M+': date.getMonth() + 1,'D+': date.getDate(),'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,'H+': date.getHours(),'m+': date.getMinutes(),'s+': date.getSeconds(),'q+': Math.floor((date.getMonth() + 3) / 3),'S': date.getMilliseconds()}var week = {'0': '\u65e5','1': '\u4e00','2': '\u4e8c','3': '\u4e09','4': '\u56db','5': '\u4e94','6': '\u516d'}if (/(Y+)/.test(fmt)) {fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))}if (/(E+)/.test(fmt)) {fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])}for (var k in o) {if (new RegExp('(' + k + ')').test(fmt)) {fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))}}return fmt
}复制代码

# $ajax

import axios from 'axios'// 跨域请求,允许保存cookieaxios.defaults.withCredentials = true
// HTTPrequest拦截,对发出的请求数据进行统一操作
axios.interceptors.request.use(config => {// 对请求参数做些什么return config
}, error => {// 对请求错误做些什么console.log('err' + error) // for debugreturn Promise.reject(error)
})
// HTTPresponse拦截,对收到的数据进行统一操作
axios.interceptors.response.use(data => {// 对返回数据进行操作return data
}, error => {return Promise.reject(new Error(error))
})
Vue.prototype.$ajax = function ajax (url = '', data = {}, type = 'GET') {type = type.toUpperCase()return new Promise(function (resolve, reject) {let promiseif (type === 'GET') {let dataStr = '' // 数据拼接字符串Object.keys(data).forEach(key => {dataStr += key + '=' + data[key] + '&'})if (dataStr !== '') {dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))url = url + '?' + dataStr}// 发送get请求promise = axios.get(url)} else {//  发送postpromise = axios.post(url, data)}promise.then(response => {resolve(response.data)}).catch(error => {reject(error)})})
}复制代码

# 数字格式化

numberComma用于分割数字,默认为3位分割,一般用于格式化金额。

Vue.prototype.$numberComma = function (source, length = 3) {source = String(source).split('.')source[0] = source[0].replace(new RegExp('(\\d)(?=(\\d{' + length + '})+$)', 'ig'), '$1,')return source.join('.')
}
复制代码

# 数字补位

numberPad用于按照位数补0,默认为2

Vue.prototype.$numberPad = function (source, length = 2) {let pre = ''const negative = source < 0const string = String(Math.abs(source))if (string.length < length) {pre = (new Array(length - string.length + 1)).join('0')}return (negative ? '-' : '') + pre + string
}复制代码

# 取随机数字

Vue.prototype.$numberRandom = function (min, max) {return Math.floor(Math.random() * (max - min + 1) + min)
}复制代码

# cookie操作

1.$cookie.get(name, [options])

  获取 cookie 值。options 参数可选,取值如下:converter 转换函数。如果所获取的 cookie 有值,会在返回前传给 converter函数进行转换。选项对象。对象中可以有两个属性:converter 和 raw. raw 是布尔值,为真时,不会对获取到的cookie 值进行 URI 解码。注:如果要获取的 cookie 键值不存在,则返回 undefined.
2.$cookie.set(name, value, [options])设置 cookie 值。参数 options 可选,可以有以下属性:path(字符串)、domain(字符串)、expires(数值或日期对象)、raw(布尔值)。当 raw 为真值时,在设置 cookie 值时,不会进行URI 编码。
3. $cookie.remove(name, [options])移除指定的 cookie.复制代码
const Cookie = {}
var decode = decodeURIComponent
var encode = encodeURIComponent
Cookie.get = function (name, options) {validateCookieName(name)if (typeof options === 'function') {options = {converter: options}} else {options = options || {}}var cookies = parseCookieString(document.cookie, !options['raw'])return (options.converter || same)(cookies[name])
}
Cookie.set = function (name, value, options) {validateCookieName(name)options = options || {}var expires = options['expires']var domain = options['domain']var path = options['path']if (!options['raw']) {value = encode(String(value))}var text = name + '=' + value// expiresvar date = expiresif (typeof date === 'number') {date = new Date()date.setDate(date.getDate() + expires)}if (date instanceof Date) {text += ' expires=' + date.toUTCString()}// domainif (isNonEmptyString(domain)) {text += ' domain=' + domain}// pathif (isNonEmptyString(path)) {text += ' path=' + path}// secureif (options['secure']) {text += ' secure'}document.cookie = textreturn text
}
Cookie.remove = function (name, options) {options = options || {}options['expires'] = new Date(0)return this.set(name, '', options)
}
function parseCookieString (text, shouldDecode) {var cookies = {}if (isString(text) && text.length > 0) {var decodeValue = shouldDecode ? decode : samevar cookieParts = text.split(/\s/g)var cookieNamevar cookieValuevar cookieNameValuefor (var i = 0, len = cookieParts.length; i < len; i++) {cookieNameValue = cookieParts[i].match(/([^=]+)=/i)if (cookieNameValue instanceof Array) {try {cookieName = decode(cookieNameValue[1])cookieValue = decodeValue(cookieParts[i].substring(cookieNameValue[1].length + 1))} catch (ex) {console.log(ex)}} else {cookieName = decode(cookieParts[i])cookieValue = ''}if (cookieName) {cookies[cookieName] = cookieValue}}}return cookies
}
function isString (o) {return typeof o === 'string'
}
function isNonEmptyString (s) {return isString(s) && s !== ''
}
function validateCookieName (name) {if (!isNonEmptyString(name)) {throw new TypeError('Cookie name must be a non-empty string')}
}
function same (s) {return s
}
Vue.prototype.$cookie = Cookie
复制代码

。。。持续更新

参考:vux工具函数

转载于:https://juejin.im/post/5afba72f5188256709616201

关于Vue中常用的工具函数封装相关推荐

  1. vue一些常用的工具函数封装

    (防抖 节流 深拷贝 数组对象去重 前端uuid生成,文件下载等函数封装) 1.校验数据类型 export const typeOf = function(obj) {return Object.pr ...

  2. 前端常用Utils工具函数库合集

    前端常用Utils工具函数库合集 在开发中,我们经常会将一些常用的代码块.功能块进行封装,为的是更好的复用.那么,被抽离出来独立完成功能,通过API或配置项和其他部分交互,便形成了插件. 函数库 Lo ...

  3. linux性能监控工具perf,Linux性能分析中常用的工具perf介绍

    今天小编要跟大家分享的文章是关于Linux性能分析中常用的工具perf介绍.系统级性能优化通常包括两个阶段:性能剖析(performance profiling)和代码优化.性能剖析的目标是寻找性能瓶 ...

  4. Vue中常用的8种v指令

    Vue中常用的8种v指令 根据官网的介绍,指令 是带有 v- 前缀的特殊属性.通过指令来操作DOM元素 指令 功能 v-text="变量/表达式" 文本的设置 字符串变量+数字可以 ...

  5. 一些常用的工具函数(snows-utils),已发npm,会陆续更新

    简介:一些常用的自定义方法 **注意:请用最新版本(之前的有些版本有小问题,目前没有找到删除指定的版本的方法)        v2.0.0之前的版本都是没有通过webpack打包的,文件相对于2.0. ...

  6. shell编程系列7--shell中常用的工具find、locate、which、whereis

    shell编程系列7--shell中常用的工具find.locate.which.whereis1.文件查找之find命令语法格式:find [路径] [选项] [操作]选项 -name 根据文件名查 ...

  7. 工作中常用,实用工具推荐!

    原文:工作中常用,实用工具推荐! Red Gate 家族 大名鼎鼎的RedGate,相信大家都不会陌生,Reflector就是它家做的.这里就不介绍了.我本地安装的是09年下的一个套装,我介绍下常用的 ...

  8. matplotlib.pyplot常用画图方式函数封装(一)——.plot绘制折线图及设置坐标轴箭头完美解决

    matplotlib.pyplot常用画图方式函数封装(一)--.plot绘制折线图及设置坐标轴箭头完美解决 py.plot常见绘图设置函数封装 绘制函数图像(完美解决坐标轴添加箭头) 绘制折线图 p ...

  9. php的正则表达式函数,php中常用的正则表达式函数

    php中常用的正则表达式函数 * preg_match() * preg_match_all() * preg_replace() * preg_filter() * preg_grep() * pr ...

最新文章

  1. 程序员如何用“撞针“拯救35亿地球人?
  2. Transforms CTM, 转换矩阵
  3. 能表示分数的计算机,分数计算器的实现
  4. python心理学实验程序_psychopy coder模式编写心理试验程序 字符程序和记录反应时...
  5. 魅族15系统是android,魅族15系列评测:性能够用王者荣耀优化
  6. 解扰matlab,数据序列扰乱与解扰MATLAB实现及性能分析—利用m序列.doc
  7. Swift面向对象基础(中)——Swift中的方法
  8. HCIE Security IPv6基础与安全技术 备考笔记(幕布)
  9. KITTI数据集可视化
  10. linux之fstab文件详解
  11. 傅里叶变换及拉普拉斯变换直观理解总结
  12. SQL Server 2008 下载地址
  13. 【金融基础设施建设01】金融基础设施建设概论(金融基础设施的定义、现状、国内外标准、基本特征、作用、风险)
  14. 光电耦合器的隔离作用是什么?
  15. 如何改善睡眠状态?建议你尝试这些方法和好物
  16. 机器学习(八):CS229ML课程笔记(4)——生成学习,高斯判别分析,朴素贝叶斯
  17. kali虚拟机如何使用桥接模式连接外网
  18. AI遮天传 DL-深度学习在计算机视觉中的应用
  19. css3中nth-child()的用法
  20. Table ‘ambari.members‘ doesn‘t exist 解决方法

热门文章

  1. 南京大学计算机学院袁健,袁健(南京大学大气科学学院教授)_百度百科
  2. 反应机理_过敏反应的发生机理及表现
  3. 消息云服务器,对方启用云消息服务器
  4. C驱动程序是怎么跑起来的
  5. 计算机应用试卷分析讲评课教案,数学试卷讲评课教案.doc
  6. ii 组合总和_40. 组合总和 II
  7. java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderL
  8. FAQ系列 | 监控平均SQL响应时长
  9. Win7 64位系统 注册 ocx控件
  10. JavaIO简单代码实例