vue 工具函数封装,持续更新。。。

4,211 阅读2分钟

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 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.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

  // 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工具函数