内容简介:只需要将绑定的这段js引入到main.js即可。绑定方法十分简单,这里不再详细说明下面列举几个常用的工具函数numberPad用于按照位数补0,默认为2
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 debug
return 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 promise
if (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 {
// 发送post
promise = 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 < 0
const 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.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
// expires
var date = expires
if (typeof date === 'number') {
date = new Date()
date.setDate(date.getDate() + expires)
}
if (date instanceof Date) {
text += ' expires=' + date.toUTCString()
}
// domain
if (isNonEmptyString(domain)) {
text += ' domain=' + domain
}
// path
if (isNonEmptyString(path)) {
text += ' path=' + path
}
// secure
if (options['secure']) {
text += ' secure'
}
document.cookie = text
return 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 : same
var cookieParts = text.split(/\s/g)
var cookieName
var cookieValue
var cookieNameValue
for (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
复制代码
获取URL中的请求参数
``
$dateFormat(url) 返回搜索参数的键值对对象
例: getsearch('http://www.longfor.com?usercode=shen&token=TKpRmNelonghu')
// { usercode: 'shen',
token: 'TKpRmNelonghu' }
复制代码
复制代码
Vue.prototype.$getsearch = function (url) {
复制代码
var obj = {} url.replace(/([^?&=]+)=([^&#]+)/g, (_, k, v) => { obj[k] = v }) return obj }
#小数截取固定位数
// 默认保留一位小数,并下舍入
$decimalNum 截取固定位数的小数
/**@param
number 处理的小数
number 保留的小数位数
number 0 对小数进行下舍入;1 四舍五入;2 上舍入
*/
例: $decimalNum(2.376186679,3,)
// 2.376
复制代码
Vue.prototype.$decimalNum = function (source, length = 1, type = 0) {
length = Math.pow(10, length)
if (type === 2) {
return Math.ceil(source * length) / length
} else if (type === 1) {
return Math.round(source * length) / length
} else {
return Math.floor(source * length) / length
}
}
复制代码
。。。持续更新
参考:vux工具函数
以上所述就是小编给大家介绍的《vue 工具函数封装,持续更新。。。》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 封装函数到实现简化版jQuery
- JS实现运动缓冲效果的封装函数示例
- Node.js 如何优雅的封装一个实用函数的 npm 包
- 封装JDBC—非框架开发必备的封装类
- SpringBlade 2.3.2 发布,增加 OSS 封装及单元测试封装
- SpringBlade 2.3.2 发布,增加 OSS 封装及单元测试封装
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Web Applications (Hacking Exposed)
Joel Scambray、Mike Shema / McGraw-Hill Osborne Media / 2002-06-19 / USD 49.99
Get in-depth coverage of Web application platforms and their vulnerabilities, presented the same popular format as the international bestseller, Hacking Exposed. Covering hacking scenarios across diff......一起来看看 《Web Applications (Hacking Exposed)》 这本书的介绍吧!
CSS 压缩/解压工具
在线压缩/解压 CSS 代码
HEX CMYK 转换工具
HEX CMYK 互转工具