资讯专栏INFORMATION COLUMN

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

Cc_2011 / 893人阅读

摘要:项目中工具函数,我们通常会添加到的原型中,这样就实现了全局函数只需要将绑定的这段引入到即可。对象中可以有两个属性和是布尔值,为真时,不会对获取到的值进行解码。参数可选,可以有以下属性字符串字符串数值或日期对象布尔值。持续更新参考工具函数

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 ");"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) ");$1.length > 2 ");"u661fu671f" : "u5468") : "") + week[date.getDay() + ""])
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ");"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)("); + 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 ");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");
Vue.prototype.$getsearch = function (url) {

var obj = {} url.replace(/([^");

#小数截取固定位数
// 默认保留一位小数,并下舍入
      $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工具函数

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/6871.html

相关文章

  • VUE防抖与节流的最佳解决方案——函数式组件

    摘要:案例持续触发事件时,并不立即执行函数,当毫秒内没有触发事件时,才会延时触发一次函数。也以函数形式暴露普通插槽。这样的场景组件用函数式组件是非常方便的。相关阅读函数式组件自定义指令前言 有echarts使用经验的同学可能遇到过这样的场景,在window.onresize事件回调里触发echartsBox.resize()方法来达到重绘的目的,resize事件是连续触发的这意味着echarts...

    OldPanda 评论0 收藏0
  • 如何构建大型的前端项目

    摘要:如何构建大型的前端项目搭建好项目的脚手架一般新开发一个项目时,我们会首先搭建好一个脚手架,然后才会开始写代码。组件化一般分为项目内的组件化和项目外的组件化。 如何构建大型的前端项目 1. 搭建好项目的脚手架 一般新开发一个项目时,我们会首先搭建好一个脚手架,然后才会开始写代码。一般脚手架都应当有以下的几个功能: 自动化构建代码,比如打包、压缩、上传等功能 本地开发与调试,并有热替换与...

    lykops 评论0 收藏0
  • 如何构建大型的前端项目

    摘要:如何构建大型的前端项目搭建好项目的脚手架一般新开发一个项目时,我们会首先搭建好一个脚手架,然后才会开始写代码。组件化一般分为项目内的组件化和项目外的组件化。 如何构建大型的前端项目 1. 搭建好项目的脚手架 一般新开发一个项目时,我们会首先搭建好一个脚手架,然后才会开始写代码。一般脚手架都应当有以下的几个功能: 自动化构建代码,比如打包、压缩、上传等功能 本地开发与调试,并有热替换与...

    plokmju88 评论0 收藏0
  • 从 0 到 1 再到 100, 搭建、编写、构建一个前端项目

    摘要:从到再到搭建编写构建一个前端项目选择现成的项目模板还是自己搭建项目骨架搭建一个前端项目的方式有两种选择现成的项目模板自己搭建项目骨架。使用版本控制系统管理源代码项目搭建好后,需要一个版本控制系统来管理源代码。 从 0 到 1 再到 100, 搭建、编写、构建一个前端项目 1. 选择现成的项目模板还是自己搭建项目骨架 搭建一个前端项目的方式有两种:选择现成的项目模板、自己搭建项目骨架。 ...

    call_me_R 评论0 收藏0
  • 从 0 到 1 再到 100, 搭建、编写、构建一个前端项目

    摘要:从到再到搭建编写构建一个前端项目选择现成的项目模板还是自己搭建项目骨架搭建一个前端项目的方式有两种选择现成的项目模板自己搭建项目骨架。使用版本控制系统管理源代码项目搭建好后,需要一个版本控制系统来管理源代码。 从 0 到 1 再到 100, 搭建、编写、构建一个前端项目 1. 选择现成的项目模板还是自己搭建项目骨架 搭建一个前端项目的方式有两种:选择现成的项目模板、自己搭建项目骨架。 ...

    wzyplus 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<