vue自定义指令

/*eslint-disable*/
import {classOf} from "./common";

export default (Vue)=>{
    Vue.directive('justify-width',{
        bind(element){
            element._$loadWidthHandler = (event)=>{
                let img = event.target;
                img.style.setProperty('width',`${(img.naturalWidth || img.width) / window.ROOT_FONT_SIZE}rem`);
            };
            element.addEventListener('load',element._$loadWidthHandler);
        },
        unbind(element){
            element.removeEventListener('load',element._$loadWidthHandler);
        }
    });
    Vue.directive('justify-height',{
        bind(element){
            element._$loadHeightHandler = (event)=>{
                let img = event.target;
                img.style.setProperty('height',`${(img.naturalHeight || img.height) / window.ROOT_FONT_SIZE}rem`);
            };
            element.addEventListener('load',element._$loadHeightHandler);
        },
        unbind(element){
            element.removeEventListener('load',element._$loadHeightHandler);
        }
    });
    Vue.directive('element-init',{
        bind(element,binding,vNode){
            let component = vNode.context;
            let elementInit = binding.expression;
            component[elementInit](element,binding.modifiers);
        },
        unbind(element,binding,vNode){

        }
    });
    Vue.directive('element-unbind',{
        bind(element,binding,vNode){

        },
        unbind(element,binding,vNode){
            let component = vNode.context;
            let elementUnbind = binding.expression;
            component[elementUnbind](element,binding.modifiers);
        }
    });
    function CustomEvent (event, params) {
        params = params || {bubbles: false, cancelable: false, detail: undefined}
        var evt = document.createEvent('CustomEvent')
        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
        return evt
    }

    (function () {
        if (typeof window.CustomEvent !== 'function') {
            CustomEvent.prototype = window.Event.prototype
            window.CustomEvent = CustomEvent
        }
    })()

    HTMLElement.prototype.$_listenWheel = function (event) {
        if (classOf(event) === 'WheelEvent') {
            var target = this
            target.$_prevScrollTop = target.$_prevScrollTop || 0
            target.$_prevScrollLeft = target.$_prevScrollLeft || 0
            if (target.$_wheelLocked) {
                return event.preventDefault()
            }
            var scrollHeight = target.scrollHeight
            var scrollWidth = target.scrollWidth
            var clientHeight = target.clientHeight
            var clientWidth = target.clientWidth
            var scrollTop = target.scrollTop
            var scrollLeft = target.scrollLeft

            try {
                let customToEvent = new CustomEvent('customscroll')
                customToEvent.deltaX = event.deltaX
                customToEvent.deltaY = event.deltaY

                if (target.$_prevScrollTop !== scrollTop && scrollTop === 0) {
                    customToEvent.toBoundary = 'top'
                }
                if (target.$_prevScrollLeft !== scrollLeft && scrollLeft === 0) {
                    customToEvent.toBoundary = 'left'
                }
                if (event.deltaY && !event.deltaX) {
                    customToEvent.details = 'to-bottom'
                    if (Math.abs(scrollTop + clientHeight - scrollHeight) <= 1) {
                        if (target.$_prevScrollTop !== scrollTop) {
                            customToEvent.toBoundary = 'bottom'
                        }
                    }
                } else if (!event.deltaY && event.deltaX) {
                    customToEvent.details = 'to-right'
                    if (Math.abs(scrollLeft + clientWidth - scrollWidth) <= 1) {
                        if (target.$_prevScrollLeft !== scrollLeft) {
                            customToEvent.toBoundary = 'right'
                        }
                    }
                }
                if (target.oncustomscroll) {
                    target.oncustomscroll(customToEvent)
                } else {
                    target.dispatchEvent(customToEvent)
                }

                if (target.$_wheelEventPrevented) {
                    event.preventDefault()
                }
            } finally {
                target.$_prevScrollTop = scrollTop
                target.$_prevScrollLeft = scrollLeft
            }
        }
    }
    /**
     * 注册load-more指令,可用在容器上,以达到当容器内容滚动在边界部位时,触发加载更多函数。
     * 可接受两个modifier.即right和bottom.不写modifier时。默认为bottom.
     * right:当内容滚动到右边界时触发
     * bottom:当内容滚动到底部时触发
     * 用法 :
     * 
* 或 *
* 或 *
* 或 *
* .... * { * myGreatLoadMoreFunc(resolve,reject,detail){ * console.log(detail);// "right" 或 “bottom” * getDataFetch(paramObj).then(resolve).catch(reject); * } * } */
Vue.directive('load-more', { bind: function (element, binding, vNode, oldVnode) { let funcName = binding.value let modifiers = binding.modifiers if (funcName) { if (!element.$_loadMoreListener) { element.$_loadMoreListener = function (event) { let detail = event.detail if (!element.$_wheelLocked) { let c = vNode.context let func = typeof funcName === 'function' ? funcName : typeof c[funcName] === 'function' ? c[funcName] : undefined if (func) { if (!modifiers.bottom && !modifiers.right) { element.$_wheelLocked = true func(function (data) { element.$_wheelLocked = undefined }, function (data) { element.$_wheelLocked = undefined }, detail) } else { for (let pro in modifiers) { if (modifiers[pro]) { if (detail === pro) { element.$_wheelLocked = true func(function (data) { element.$_wheelLocked = undefined }, function (data) { element.$_wheelLocked = undefined }, detail) } } } } } } } /* element.$_wheelListener = function (event) { var target = this; if (target.$_wheelLocked) { event.preventDefault();//阻止页面继续滚动 } var scrollHeight = target.scrollHeight; var scrollWidth = target.scrollWidth; var clientHeight = target.clientHeight; var clientWidth = target.clientWidth; var scrollTop = target.scrollTop; var scrollLeft = target.scrollLeft; if (scrollTop + clientHeight === scrollHeight) { if (target.$_prevScrollTop !== scrollTop) { !target.$_wheelLocked && target.dispatchEvent(new CustomEvent('scroll-to-load-more', { detail: 'bottom' })); } } if (scrollLeft + clientWidth === scrollWidth) { if (target.$_prevScrollLeft !== scrollLeft) { !target.$_wheelLocked && target.dispatchEvent(new CustomEvent('scroll-to-load-more', { detail: 'right' })); } } target.$_prevScrollTop = scrollTop; target.$_prevScrollLeft = scrollLeft; }; */ element.addEventListener('scroll-to-load-more', element.$_loadMoreListener) } if (!element.$_wheelListener) { element.$_wheelListener = function (event) { this.$_listenWheel(event) } element.addEventListener('wheel', element.$_wheelListener) } if (!element.$_customScrollListenerLoadMore) { element.$_customScrollListenerLoadMore = function (customScrollEvent) { if (customScrollEvent.toBoundary === 'bottom' || customScrollEvent.toBoundary === 'right') { !this.$_wheelLocked && this.dispatchEvent(new CustomEvent('scroll-to-load-more', { detail: customScrollEvent.toBoundary })) } } element.addEventListener('customscroll', element.$_customScrollListenerLoadMore) } } else { throw new Error('v-scroll-to-load-more has no value!!!') } }, unbind: function (element, binding, vNode, oldVnode) { element.removeEventListener('scroll-to-load-more', element.$_loadMoreListener) element.removeEventListener('wheel', element.$_wheelListener) element.removeEventListener('customscroll', element.$_customScrollListenerLoadMore) element.$_loadMoreListener = null element.$_wheelListener = null element.$_customScrollListenerLoadMore = null } } ); function insertNoScrollbarCssRule2Head (cssRule) { let head = document.head let style = document.getElementById('styleForNoScrollbar') if (!style) { style = document.createElement('style') style.setAttribute('id', 'styleForNoScrollbar') head.appendChild(style) } style.innerText += cssRule } /** * 注册VUE 指令,该指令使注册组件或元素滚动条消失,但不影响滚动 * 用法: * * * * * * 或者 * * * 或者 */ Vue.directive('no-scrollbar', { bind: function (element, binding, vNode, oldVnode) { element.setAttribute('data-v-no-scroll', 'ns-' + new Date().getTime()) let modifiers = binding.modifiers// ['bottom','right']其中的一个或两个或两个都没 if (/webkit/i.test(window.navigator.userAgent)) { // 如果是webkit内核浏览器,直接加伪元素选择器::-webkit-scrollbar{display:none}就可以了 let css = '[data-v-no-scroll=' + element.getAttribute('data-v-no-scroll') + ']::-webkit-scrollbar{display:none;}' insertNoScrollbarCssRule2Head(css) if (Object.keys(modifiers).length > 0) { // console.warn('modifiers ignored because webkit browser can make scrollbar disappear however it also makes both scrollbars disappear.'); } return } else { let regExp = /firefox\/(\d+(.\d+)?)/i let exc = regExp.exec(window.navigator.userAgent) if (exc) { let version = exc[1] if (version > 64) { // firefox65以上支持scrollbar-width css属性 let css = '[data-v-no-scroll=' + element.getAttribute('data-v-no-scroll') + ']{scrollbar-width:none;}' insertNoScrollbarCssRule2Head(css) if (Object.keys(modifiers).length > 0) { // console.warn('modifiers ignored because firefox browser can make scrollbar disappear however it also makes both scrollbars disappear.'); } return } } } function makeNoScrollbar (where) { switch (where) { case 'right': case 'y': element.style.setProperty('overflow-y', 'hidden') break case 'bottom': case 'x': element.style.setProperty('overflow-x', 'hidden') break default: element.style.setProperty('overflow', 'hidden') break } } let set = false modifiers && ((mdfs) => { for (let pro in mdfs) { if (mdfs.hasOwnProperty(pro)) { makeNoScrollbar(pro) set = true } } })(modifiers) !set && makeNoScrollbar(null) if (!element.$_customScrollListener) { element.$_customScrollListener = function (event) { if (event.details === 'to-bottom') { let maxScrollTop = this.maxScrollTop let newScrollTop = Math.max(Math.min(maxScrollTop, this.scrollTop + event.deltaY / 8), 0) this.scrollTop = newScrollTop if (maxScrollTop === 0 || event.toBoundary === 'bottom' || event.toBoundary === 'top' || event.toBoundary === 'right' || event.toBoundary === 'left') { this.$_wheelEventPrevented = false } else { this.$_wheelEventPrevented = true } } else if (event.details === 'to-right') { let maxScrollLeft = this.maxScrollLeft let newScrollLeft = Math.max(Math.min(maxScrollLeft, this.scrollLeft + event.deltaX / 8), 0) this.scrollLeft = newScrollLeft if (maxScrollLeft === 0 || event.toBoundary === 'bottom' || event.toBoundary === 'top' || event.toBoundary === 'right' || event.toBoundary === 'left') { this.$_wheelEventPrevented = false } else { this.$_wheelEventPrevented = true } } } element.addEventListener('customscroll', element.$_customScrollListener) } if (!element.$_wheelListener) { element.$_wheelListener = function (event) { element.$_listenWheel(event) } element.addEventListener('wheel', element.$_wheelListener) } }, unbind: function (element, binding, vNode, oldVnode) { element.removeEventListener('wheel', element.$_wheelListener) element.removeEventListener('customscroll', element.$_customScrollListener) element.$_wheelListener = null element.$_customScrollListener = null } }); /** * 注册控件单击指令,当鼠标单击时,触发函数。(已排除 双击——用户迅速按下抬起鼠标键至少两次,以及 选中——用户按下鼠标键并拖动鼠标的情况。) * 用法: * 简单用法 * * * * 稍微复杂的用法 * * {console.log('myArr is ',myArr,'.It\'s available here! And because rowIndex is '+rowIndex,' so the myArr['+rowIndex+'] = '+myArr[rowIndex])}'> * * * * * * * * * *
11121314
21222324
31323334
* * care接受prop字段以及excludeSelectors/targetSelector字段 * prop 是被点目标元素的属性名,excludeSelectors 是要排除在外的元素选择器,targetSelector 是点击认可的目标元素选择器 * * 因此当点击表格的每一行的第一第二列时,不会触发click,当点击每一行,且不是第一第二列时,将会触发click。 * 注意click:(rowIndex)=>{console.log(rowIndex)},意思是点击到targetSelector的元素时,将会把刚才的prop属性对应的值传回来。例子里每一行的索引 rowIndex。 * 当点击第一行,回传为0,点击第二行,回传为1,以此类推. */
Vue.directive('fix-click', { bind: function (element, binding, vNode, oldVnode) { let directiveValue = binding.value let modifiers = binding.modifiers let c = vNode.context let func = typeof directiveValue === 'function' ? directiveValue : typeof directiveValue['click'] === 'function' ? directiveValue['click'] : undefined let care = directiveValue.care let targetSelector = care && care.targetSelector let excludeSelectors = care && care.excludeSelectors let prop = care && care.prop element.$_mouseDownCall = function (event) { if (event.button === 0) { if (!this.$_upTime) { this.$_upTime = 0 } let time = new Date().getTime() let deltaTime = time - this.$_upTime this.$_doubleClicked = deltaTime < 250 if (this.$_doubleClicked) { // 在短时间内又Mouse down了一次,意味着用户是想触发双击事件或者N(N>1)击事件 window.clearTimeout(this.$_clickTimeout) } this.$_PageX0 = this.$_PageX = event.pageX this.$_PageY0 = this.$_PageY = event.pageY } } element.$_mouseMoveCall = function (event) { if (event.button === 0) { this.$_PageX = event.pageX this.$_PageY = event.pageY } } element.$_mouseUpCall = function (event) { if (event.button === 0) { this.$_upTime = new Date().getTime() this.$_PageX = event.pageX this.$_PageY = event.pageY let disSquare = Math.pow(this.$_PageX - this.$_PageX0, 2) + Math.pow(this.$_PageY - this.$_PageY0, 2) if (disSquare < 36) { // 鼠标起始位置超过一定距离,认为用户是在鼠标拖动操作,例如目标选中 if (!this.$_doubleClicked) { this.$_clickTimeout = setTimeout(function () { if (!this.$_doubleClicked) { if (!targetSelector) { func && func() } else { if (!excludeSelectors || !(excludeSelectors.some((s) => { return event.target.closest(s) }))) { let target = event.target.closest(targetSelector) if (target) { if (prop) { func && func(target[prop]) } else { func && func(target) } } else { } } } } window.clearTimeout(this.$_clickTimeout) }.bind(this), 250) } } } } element.addEventListener('mouse' + 'down', element.$_mouseDownCall) element.addEventListener('mouse' + 'up', element.$_mouseUpCall) element.addEventListener('mouse' + 'move', element.$_mouseMoveCall) }, unbind: function (element, binding, vNode, oldVnode) { element.removeEventListener('mouse' + 'down', element.$_mouseDownCall) element.removeEventListener('mouse' + 'up', element.$_mouseUpCall) element.removeEventListener('mouse' + 'move', element.$_mouseMoveCall) element.$_mouseDownCall = null element.$_mouseUpCall = null element.$_mouseMoveCall = null } }); }
/*eslint-disable*/
import moment from "moment";

/**
 * 传入对象,获取对象的类
 * @param obj 任何对象
 * @returns {*} 对象的类,确切的说,是对象对应的构造函数名称
 *
 * //for instance:
 *
 * var obj = {};
 * console.log(classOf(obj));  // expected output --->  Object
 *
 * var obj = [1,2,3];
 * console.log(classOf(obj));  // expected output --->  Array
 *
 * var obj = new Date();
 * console.log(classOf(obj));  // expected output --->  Date
 *
 * var obj = 12;
 * console.log(classOf(obj));  // expected output --->  number
 *
 * var obj = 'abc';
 * console.log(classOf(obj));  // expected output --->  string
 *
 * var obj = null;
 * console.log(classOf(obj));  // expected output --->  null
 *
 * var obj = undefined;
 * console.log(classOf(obj));  // expected output --->  undefined
 *
 * var obj = true;
 * console.log(classOf(obj));  // expected output --->  boolean
 *
 * function Dog(){ }
 * var obj = new Dog();
 * console.log(classOf(obj));  // expected output --->  Dog
 *
 */
export function classOf(obj) {
  if (obj === null) {
    return 'null';
  } else if (typeof obj !== 'object') {
    return typeof obj;
  } else {
    if (obj.constructor.name) {
      return obj.constructor.name.trim();
    } else {
      let funcStr = obj.constructor.toString();
      if (funcStr.indexOf('function') > -1) {
        return funcStr.substring(9, funcStr.indexOf('(')).trim();
      } else if (funcStr.indexOf('[object') > -1) {
        return funcStr.substring(8, funcStr.length - 1).trim();
      }
    }
  }
}

/**
 * 比较两个对象是否相等
 * @param a any
 * @param b any
 * @returns {*|boolean}
 *
 * var a = null,b = null;
 * itEqual(a, b) // expected output ---> true
 *
 * var a = undefined,b = undefined;
 * itEqual(a, b) // expected output ---> true
 *
 * var a = null,b = undefined;
 * itEqual(a, b) // expected output ---> true
 *
 * var a = 11,b = 11;
 * itEqual(a, b) // expected output ---> true
 *
 * var a = 11,b = '11';
 * itEqual(a, b) // expected output ---> true
 *
 * var a = {name:'Sam',age:30},b = {name:'Sam',age:30};//会深入比较字段是否一致,以及每个字段是否相等
 * itEqual(a, b) // expected output ---> true
 *
 * var a = {name:'Sam',age:30},b = {name:'Sam',age:20};//会深入比较字段是否一致,以及每个字段是否相等
 * itEqual(a, b) // expected output ---> false
 *
 */
export function itEqual(a, b) {
  let r = (function (obj, other) {
    let type = classOf(obj).toLowerCase();
    let typeOther = classOf(other).toLowerCase();
    if (type === typeOther) {
      switch (type) {
        case 'null':
        case 'undefined':
          return typeOther === 'null' || typeOther === 'undefined';
        case 'number':
        case 'string':
          return obj + '' === other + '';
        default:
          return JSON.stringify(obj) === JSON.stringify(other);
      }
    } else if (typeOther === 'number' && type === 'number'
      || typeOther === 'string' && type === 'string'
      || typeOther === 'string' && type === 'number'
      || typeOther === 'number' && type === 'string') {
      return obj + '' === other + '';
    } else {
      return false;
    }
  }(a, b));
  return r;
}

/**
 * 清空对象
 * @param obj any
 * @param p 需要清除的某个属性
 * @param excludedProps 一些不能清除的属性
 * @returns {undefined}
 *
 * var a = null;
 * emptyObj(a) // expected output ---> null;
 *
 * var a = 'str';
 * emptyObj(a) // expected output ---> '';
 *
 * var a = 123;
 * emptyObj(a) // expected output ---> 0;
 *
 * var a = true;
 * emptyObj(a) // expected output ---> false;
 *
 * var a = [1,2,3,4];
 * emptyObj(a) // expected output ---> [];
 *
 * var a = {name:'Sam',age:30,married:true};
 * emptyObj(a) // expected output ---> {name:'',age:0,married:false};
 *
 * var a = {name:'Sam',age:30,married:true};
 * emptyObj(a,'age') // expected output ---> {name:'Sam',age:0,married:true};
 *
 * var a = {name:'Sam',age:30,married:true,kids:[{name:'Joe',age:3},{name:'Alex',age:12}]};
 * emptyObj(a) // expected output ---> {name:'',age:0,married:false,kids:[]};
 *
 * var a = {name:'Sam',age:30,married:true,kids:[{name:'Joe',age:3},{name:'Alex',age:12}]};
 * emptyObj(a,null,['kids']) // expected output ---> {name:'',age:0,married:false,kids:[{name:'Joe',age:3},{name:'Alex',age:12}]};
 *
 */
export function emptyObj(obj, p, excludedProps) {
  if (obj) {
    if (p) {
      if (excludedProps && excludedProps.some && excludedProps.some(function (prop) {
        return prop === p
      })) {
        return;
      }
      let type = classOf(obj[p]).toLowerCase();
      switch (type) {
        case 'string':
          obj[p] = '';
          return;
        case 'object':
          for (let pro in obj[p]) {
            if (pro.indexOf('_') === 0 || !obj[p].hasOwnProperty(pro)) {
              continue;
            }
            emptyObj(obj[p], pro, excludedProps);
          }
          return;
        case 'number':
          obj[p] = 0;
          return;
        case 'boolean':
          obj[p] = false;
          return;
        case 'date':
          obj[p].setTime(new Date().getTime());
          return;
        case 'array':
          obj[p].splice(0);
          return;
      }
      return obj[p] = undefined;
    } else {
      for (let pro in obj) {
        if (excludedProps && excludedProps.some && excludedProps.some(function (prop) {
          return prop === pro
        }) || pro.indexOf('_') === 0 || !obj.hasOwnProperty(pro)) {
          continue;
        }
        emptyObj(obj, pro, excludedProps);
      }
    }
  }
}

export function clearVueData(vue, excludedProps) {
  let data = vue.$data;
  emptyObj(data, null, excludedProps);
}

/**
 * 模拟Map对象
 * @constructor
 *
 * var itMap = new ITMap();
 *
 * itMap.put('name','Alexander');
 * itMap.put('age','30');
 * itMap.put('married','0');
 *
 * itMap.get('name');// expected output --> Alexander
 * itMap.get('age');// expected output --> 30
 * itMap.get('married');// expected output --> 0
 *
 * itMap.clear();//清空
 *
 * itMap.get('name');// expected output --> undefined
 * itMap.get('age');// expected output --> undefined
 * itMap.get('married');// expected output --> undefined
 */
export function ITMap() {
  if (this instanceof ITMap) {
    this.keys = [];
    this.values = []
  } else {
    return new ITMap();
  }
}

ITMap.prototype.clear = function(){
  this.keys = [];
  this.values = []
};
ITMap.prototype.put = function(key, value){
  let index = -1;
  this.keys.some((k, i) => {
    if (k === key) {
      index = i;
      return true
    }
  });
  if (index!==-1) {
    this.values[index] = value;
  } else {
    this.keys.push(key);
    this.values.push(value);
  }
};
ITMap.prototype.get = function(key) {
  if (this.keys && this.keys.length) {
    let index = -1;
    this.keys.some((k, i) => {
      if (k === key) {
        index = i;
        return true;
      }
    });
    return this.values && this.values[index];
  }
};
/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #3 - July 13th, 2017
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

export var itDocCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          /*
          Note: Despite officially defined in RFC 6265, the use of `max-age` is not compatible with any
          version of Internet Explorer, Edge and some mobile browsers. Therefore passing a number to
          the end parameter might not work as expected. A possible solution might be to convert the the
          relative time to an absolute time. For instance, replacing the previous line with:
          */
          /*
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; expires=" + (new Date(vEnd * 1e3 + Date.now())).toUTCString();
          */
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};
export function getSearchValue(name,search) {
  search = search || location.search;
  let value = undefined;
  if(search){
    search = search.substr(1);
    let searchArgs = search.split(/&/);
    if(searchArgs){
      searchArgs.some((searchArg)=>{
        if(searchArg){
          let nameAndValue = searchArg.split(new RegExp(`${name}=`));
          if(nameAndValue && nameAndValue.length>1){
            value = nameAndValue[1];
            return true
          }
        }
      })
    }
  }
  return value;
}
export function replaceRouteWithParamsObject (vueComponent, paramsObject, noReplace, onComplete, onAbort) {
    if (!paramsObject) {
        throw new Error('paramsObject can not be undefined or null.')
    }
    let preParamsObject = getParamsObjectFromRoute(vueComponent)
    if (preParamsObject) {
        paramsObject = {
            ...preParamsObject,
            ...paramsObject
        }
    }
    paramsObject = JSON.stringify(paramsObject)
    paramsObject = encodeURIComponent(paramsObject)
    let forReplace = {
        name: vueComponent.$route.name,
        params: {
            ...vueComponent.$route.params,
            extraParams: paramsObject
        }
    }
    if (vueComponent.$route.meta) {
        forReplace.meta = {...vueComponent.$route.meta}
    }
    if (!noReplace) {
        vueComponent.$router.replace(forReplace, onComplete, onAbort)
    } else {
        return forReplace
    }
}
export function getParamsObjectFromRoute (vueComponent, name) {
    let paramsObject = vueComponent.$route.params.extraParams
    if (paramsObject) {
        paramsObject = decodeURIComponent(paramsObject)
        paramsObject = JSON.parse(paramsObject)
        if (name) {
            return paramsObject[name]
        } else {
            return paramsObject
        }
    }
}
export function formatDate(date,onlyDate,seperatorPre,seperatorSuf){
    if(!(date instanceof Date)){
        date = new Date();
    }
    var seperator1 = seperatorPre?seperatorPre:"-";
    var seperator2 = seperatorSuf?seperatorSuf:":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate;
    if(onlyDate){
        currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
    }else{
        currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
    }
    return currentdate;
}
/**
 *从headers中获取附件的文件名
 * @param headers
 * @returns {undefined}
 */
export function getContentDispositionFileName(headers, defaultName) {
    var contentDisposition = headers.get ? headers.get('Content-Disposition') : headers['Content-Disposition']
        || headers.get ? headers.get('content-Disposition') : headers['content-Disposition']
        || headers.get ? headers.get('content-disposition') : headers['content-disposition'];
    var regExp = /(?:filename=)([^;]+)(;?)/i;
    var fileName = undefined;
    var matches = contentDisposition && contentDisposition.match(regExp);
    if (matches && matches.length > 1) {
        fileName = matches[1];
        fileName = decodeURIComponent(fileName);
    }
    return fileName ? fileName : defaultName;
}

/**
 * 保存blob文件
 * @param blob
 * @param fileName
 */
export function saveBlobFile(blob, fileName) {
    if (window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {
        var objectUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style.setProperty('display', 'none');
        a.href = objectUrl;
        a.download = fileName;
        a.click();
        setTimeout(function () {
            document.body.removeChild(a);
            URL.revokeObjectURL(objectUrl);
        })
    }
}
window._$_KEY_CNT = 0;
export function generateKey() {
    return `${new Date().getTime()}${Math.floor(Math.random() * (10000 - 1000)) + 1000}${window._$_KEY_CNT++}`
}

/**
 * 文件的大小
 * @param sizeSum
 * @param sizeUnit
 */
export function reasonableFileSizeUnit(sizeSum,sizeUnit) {
    sizeUnit = sizeUnit || 'b';
    let unit = 'b';
    if (sizeUnit === 'b' && sizeSum > 1024) {
        unit = 'Kb';
        sizeSum /= 1024;
    }
    if ((sizeUnit === 'b' || sizeUnit === 'Kb') && sizeSum > 1024) {
        unit = 'Mb';
        sizeSum /= 1024;
    }
    return {
        size: sizeSum.toFixed(1) - 0,
        unit
    };
}
export function getIEVersion() {
    var rv = -1;
    var ua = window.navigator.userAgent;
    var re = null;
    if (window.navigator.appName === 'Microsoft Internet Explorer') {
        re = new RegExp('MSIE ([0-9]+[\.0-9]*)');
        if (re.exec(ua) !== null) {
            rv = parseFloat(RegExp.$1);
        }
    } else if (window.navigator.appName === 'Netscape') {
        re = new RegExp('Trident/.*rv:([0-9]+[\.0-9]*)');
        if (re.exec(ua) !== null) {
            rv = parseFloat(RegExp.$1);
        }
    }
    return rv;
}
export function readFileAsDataURL(file) {
    return new Promise((resolve, reject)=>{
        let fileReader = new FileReader();
        fileReader.onload = (event)=>{
            resolve(fileReader.result);
        };
        fileReader.onerror = (event)=>{
            reject(event);
        };
        fileReader.readAsDataURL(file);
    });
}
export function downloadFileByAnchor(href) {
    let a = document.createElement('a');
    a.style.setProperty('display','none');
    a.setAttribute('href',href);
    a.setAttribute('target','_blank');
    document.body.appendChild(a);
    a.click();
    setTimeout(()=>{
        document.body.removeChild(a);
    });
}
export function groupArrayByColumnCnt(array,columnCnt) {
    let arr = [];
    let rowCnt = Math.ceil(array.length / columnCnt);
    for (let i = 0;i < rowCnt;i++){
        arr.push([]);
    }
    for (let i = 0;i < array.length;i++){
        let rowIndex = Math.floor(i / columnCnt);
        let columnIndex = i % columnCnt;
        arr[rowIndex][columnIndex] = array[i];
    }
    return arr;
}
export function dateFormat(date,format) {
    if(date){
        format = format ? format :'YYYY-MM-DD HH:mm:ss';
        return moment(date).format(format);
    }
}

你可能感兴趣的:(vue.js,javascript,前端)