The utility functions in the Vue project, which we usually add to the prototype of the Vue, implement global functions

import Vue from 'vue'
Vue.prototype.$tools = function() {}Copy the code

Just import the bound js to main.js. The binding method is quite simple and won’t be detailed here

Here are some common utility functions

$dateFormat Event formatting function, much lighter than 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.The $1, (date.getFullYear() + ' ').substr(4 - RegExp.The $1.length))
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.The $1, ((RegExp.The $1.length > 1) ? (RegExp.The $1.length > 2 ? '\u661f\u671f' : '\u5468') : ' ') + week[date.getDay() + ' '])}for (var k in o) {
    if (new RegExp('(' + k + ') ').test(fmt)) {
      fmt = fmt.replace(RegExp.The $1, (RegExp.The $1.length === 1) ? (o[k]) : (('00' + o[k]).substr((' ' + o[k]).length)))
    }
  }
  return fmt
}
Copy the code

$ajax

import axios from 'axios'/ / cross-domain request, allow to save cookieaxios. Defaults. WithCredentials =true/ / HTTPrequest interception, to request data from the unified operation axios. Interceptors. Request. Use (config = > {/ / the request parameters doreturnConfig}, error => {// What to do about the request error console.log('err' + error) // for debug
  returnPromise. Reject (error)}) / / HTTPresponse interception, the received data are unified operation axios. Interceptors. Response. Use (data = > {/ / the return datareturn 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 = ' '// Data stitching string Object.keys(data).foreach (key => {dataStr += key +'=' + data[key] + '&'
      })
      if(dataStr ! = =' ') {
        dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
        url = url + '? '+ dataStr} // Send get request promise = axios.get(url)}else{// send post promise = axios.post(url, data) } promise.then(response => { resolve(response.data) }).catch(error => { reject(error) }) }) }Copy the code

Number formatting

NumberComma is used to split numbers, which defaults to three digits, and is generally used to format amounts.Copy the code
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('. ')}Copy the code

Digital covering

NumberPad is used to complement zeros by number of digits. The default value is 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 ? The '-' : ' ') + pre + string
}
Copy the code

Take a random number

Vue.prototype.$numberRandom = function (min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}
Copy the code

Cookie operation

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

Gets the cookie value. Options The options are optional: Converter conversion function. If the obtained cookie has a value, it is passed to the Converter function for conversion before returning. Option object. There can be two properties in the object: Converter and RAW. Raw is a Boolean value, and when true, the obtained cookie value will not be URI decoded. Note: If the cookie key does not exist, undefined.2 is returned.Cookie. remove(name, [options]) removes the specified 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) {
  returnisString(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
Copy the code

Gets the request parameters in the URL

$dateFormat(URL) returns key-value pairs of search parameters:  getsearch('http://www.longfor.com?usercode=shen&token=TKpRmNelonghu') // { usercode: 'shen', token: 'TKpRmNelonghu' }Copy the code
Copy the code
Vue.prototype.$getsearch = function (url) {
Copy the code

var obj = {} url.replace(/([^?&=]+)=([^&#]+)/g, (_, k, v) => { obj[k] = v }) return obj }

# Decimals are fixed digits// By default, one decimal digit is reserved and rounded down$decimalNum/**@param number Specifies the number of decimal digits to be reserved. 1 round; 2 round */ example:$decimalNum/ / 2.376 (2.376186679, 3,)Copy the code
    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
    }
  }
Copy the code

. Continuously updated

Reference: VUX utility functions