下面具体介绍在vue中使用全局拦截器的使用方法。将以下代码放在 your-project/src/util/currency.js
const digitsRE = /(\d{3})(?=\d)/g
export function currency (value, currency, decimals) {
value = parseFloat(value)
if (!isFinite(value) || (!value && value !== 0)) return ''
currency = currency != null ? currency : '$'
decimals = decimals != null ? decimals : 2
var stringified = Math.abs(value).toFixed(decimals)
var _int = decimals
? stringified.slice(0, -1 - decimals)
: stringified
var i = _int.length % 3
var head = i > 0
? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
: ''
var _float = decimals
? stringified.slice(-1 - decimals)
: ''
var sign = value < 0 ? '-' : ''
return sign + currency + head +
_int.slice(i).replace(digitsRE, '$1,') +
_float
}
在src/main.js里面写入以下代码
import {currency} from './util/currency'
Vue.filter('currency', currency);
然后在展示价格的地方设置过滤器即可,如以美元符号显示,默认展示两位小数。比如2000可以格式化为$2,000.00
{{item.productPrice | currency('$')}}
也可以在组件中单独设置过滤器:
import {currency} from './util/currency'
在页面中导入之后写上
filters:{
currency: currency
}
/**
* Created by jacksoft on 17/4/26.
*/
Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
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;
}
module.exports = {};
$ npm install vue-lazyload -D
在main.js中写入
import Vue from 'vue'
import App from './App'
import VueLazyLoad from 'vue-lazyload'
Vue.config.productionTip = false
Vue.use(VueLazyLoad, {
loading: '/static/loading-svg/loading-bas.svg'
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
最后控制loading真假即可
<div class="load-more" v-if="loading">
<img src="../../static/loading-svg/loading-spinning-bubbles.svg" />
</div>
<img v-lazy="'static/'+ item.productImg" alt="">
function objDeepCopy(source) {
var sourceCopy = source instanceof Array ? [] : {};
for (var item in source) {
sourceCopy[item] =
typeof source[item] === "object"
? this.objDeepCopy(source[item])
: source[item];
}
return sourceCopy;
}
export function get(url, data) {
return request(url, "GET", data);
}
export function post(url, data) {
return request(url, "POST", data);
}
// wx.request({
// //测试获得后台接口数据
// url:
// config.requestUrl +
// "/data/user_grow/detail_data.do?product_id=0I3008C61U1RWX0W&platform=Android&startDate=2018-06-12&endDate=2018-07-11&app_version=total&channel=total&group_id=total&group_by=statis_day&order_by=statis_day%20desc",
// header: {
// "content-type": "application/json",
// wxappkey: key //步骤3:请求头部带上key
// },
// success: function(res) {
// console.log("数据信息:", res);
// },
// fail: function(res) {
// console.log("fail!!! ", res.data);
// }
// });
function request(
url,
method,
data,
header = {
"content-type": "application/json;charset=utf-8",
wxappkey: wx.getStorageSync("key")
}
) {
return new Promise((resolve, reject) => {
wx.showLoading({
title: "加载中"
});
wx.request({
data,
method,
header,
// url: config.host + url,
url: config.requestUrl + url,
success: function(res) {
console.log(res);
// if (res.data.data.ret_code === 0 && res.data.code === 0) {
if (res.data.ret_code === 0 || url === "/dictdata") {
// 这个接口没有返回ret_code值
resolve(res.data);
} else {
// showModal('失败', res.data.data.data.msg)
console.log("url", url);
showModal("失败", res.data.msg ? res.data.msg : "服务器数据出错");
reject(res.data);
}
},
fail: function(res) {
console.log("fail!!! ", res);
showModal("失败", res.data ? res.data : "error");
},
complete: function() {
wx.hideLoading();
}
});
});
}
function getBetweenDateStr(start, end) {
var result = [];
var beginDay = start.split("-");
var endDay = end.split("-");
var diffDay = new Date();
var dateList = new Array();
var i = 0;
diffDay.setDate(beginDay[2]);
diffDay.setMonth(beginDay[1] - 1);
diffDay.setFullYear(beginDay[0]);
result.push(start);
while (i == 0) {
var countDay = diffDay.getTime() + 24 * 60 * 60 * 1000;
diffDay.setTime(countDay);
dateList[2] = diffDay.getDate();
dateList[1] = diffDay.getMonth() + 1;
dateList[0] = diffDay.getFullYear();
if (String(dateList[1]).length == 1) {
dateList[1] = "0" + dateList[1];
}
if (String(dateList[2]).length == 1) {
dateList[2] = "0" + dateList[2];
}
result.push(dateList[0] + "-" + dateList[1] + "-" + dateList[2]);
if (
dateList[0] == endDay[0] &&
dateList[1] == endDay[1] &&
dateList[2] == endDay[2]
) {
i = 1;
}
}
return result;
}
// 格式化数字,value为传入数字,currency为需要添加的前缀货币符号($等),decimals为保留几位小数(四舍五入),如将formatNum(2956834, '', 0)格式化成295,683,4
function formatNum(value, currency = "", decimals = 0) {
// 数值不存在则转换为--
if (!value && value !== 0) {
return "--";
}
if (parseInt(value) !== value) {
// 如果是小数,默认保存两位
decimals = 2;
}
const digitsRE = /(\d{3})(?=\d)/g;
value = parseFloat(value);
if (!isFinite(value) || (!value && value !== 0)) return "";
currency = currency != null ? currency : "$";
decimals = decimals != null ? decimals : 2;
var stringified = Math.abs(value).toFixed(decimals);
var _int = decimals ? stringified.slice(0, -1 - decimals) : stringified;
var i = _int.length % 3;
var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? "," : "") : "";
var _float = decimals ? stringified.slice(-1 - decimals) : "";
var sign = value < 0 ? "-" : "";
return (
sign + currency + head + _int.slice(i).replace(digitsRE, "$1,") + _float
);
}
export function getAnyDay(count, date) {
// date必须包含-的格式
count = count || 0;
var dd, y, m, d, day, dateArr;
if (date) {
dateArr = date.split("-");
day = new Date().setFullYear(
parseInt(dateArr[0]),
parseInt(dateArr[1]) - 1,
parseInt(dateArr[2])
);
dd = new Date(day + count * 24 * 60 * 60 * 1000);
} else {
dd = new Date();
dd.setDate(dd.getDate() + count);
}
y = dd.getFullYear();
m = dd.getMonth() + 1;
d = dd.getDate();
m = m < 10 ? "0" + m : m;
d = d < 10 ? "0" + d : d;
return y + "-" + m + "-" + d;
}
export function getAnyMonth(count,month){
count = count || 0;
var date, yy, mm;
if(month){
yy = parseInt(month.substring(0,4));
mm = parseInt(month.substring(month.length-2,month.length))+count;
}else{
date=new Date();
yy=date.getFullYear();
mm=date.getMonth()+count+1;
}
if(mm<=0){
mm=mm+12;
yy--;
}else if(mm>12){
var n = Math.floor(mm/12);
mm = mm-12*n;
yy += n;
}
if(mm<10){
mm = '0'+mm;
}
return yy + '-' + mm;
}
function checkNumber(theObj) {
var reg = /^-?[0-9]+.?[0-9]*$/;
if (reg.test(theObj)) {
return true;
}
return false;
}
Object.assign
,在此做兼容 if (typeof Object.assign != 'function') {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assign", {
value: function assign(target, varArgs) { // .length of function is 2
'use strict';
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}
function getInputFile(inputId) {
// 获取文件对象(该对象的类型是[object FileList],其下有个length属性)
var fileEle = $('#' + inputId)[0];
var fileObj = null;
if (fileEle.files) {
// 如果文件对象的length属性为0,就是没文件
if (fileEle.files.length === 0) {
console.log('没选择文件');
return false;
};
fileObj = fileEle.files[0];
} else {
/*
低版本IE由于JS安全问题,不允许JS访问本地文件,所以无法获取files
对于低版本的IE可以使用ActiveXObject获取文件对象, 但是默认情况下
ActiveXObject为不可用的, 所以要想使用此对象要先启用设置, 即:
Tools(工具) / Internet options(选项) / Security(安全) / Custom level(自定义级别)
找到"Initialize and script ActiveX controls not marked as safe for scripting"
设置为"Enable(not secure)"即可.
*/
var fso = new ActiveXObject("Scripting.FileSystemObject");
/*
1. 获取文件路径
出于安全性的考虑,低版本IE上传文件时屏蔽了真实的本地文件路径,
以C:\fakepath\**取而代之, 所以默认情况下通过fileEle.value 不能获取到
文件的真实路径.
如果想获取真实路径, 有两种方式:
1. 通过设置IE的安全设置, 即:
Tools(工具) / Internet options(选项) / Security(安全) / Custom level(自定义级别)
找到"Include local directory path when uploading files to a server"
设置为的"Enable"
2. 使用JS获取, 即:
fileEle.select().blur();
var filePath = document.selection.createRange().text;
*/
fileEle.select();
fileEle.blur();
var filePath = document.selection.createRange().text;
/*
FileExists: 判断 文件是否存在
GetFile: 获取文件对象
*/
if (fso.FileExists(filePath)) {
fileObj = fso.GetFile(filePath);
}
/*
通过文件对象可以获取文件的基本信息, 如:
*/
// console.info("文件类型:" + fileObj.type);
// console.info("文件名称:" + fileObj.name);
// console.info("文件大小:" + fileObj.size);
}
// console.log(fileObj)
return fileObj;
};
function escapeValue(v) {
var entry = {
'\'': ''',
'"': '"',
'<': '<',
'>': '>'
};
v = v.replace(/(['")-><&\\\/\.])/g, function ($0) {
return entry[$0] || $0;
});
return v;
}
function parseParam(param, key){
var paramStr="";
if(param instanceof String||param instanceof Number||param instanceof Boolean){
paramStr+="&"+key+"="+encodeURIComponent(param);
}else{
$.each(param,function(i){
var k=key==null?i:key+(param instanceof Array?"["+i+"]":"."+i);
paramStr+='&'+parseParam(this, k);
});
}
return paramStr.substr(1);
};
function downFile(opts) {
opts.method = opts.method || 'GET'
var url = opts.url
var xhr = new XMLHttpRequest()
xhr.open(opts.method, url, true)
xhr.responseType = 'blob'
var formData = new FormData()
for (var i in opts.data) {
formData.append(i, opts.data[i])
}
// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function () {
// 请求完成
console.log('this', this)
if (this.status === 200) {
var blob = this.response
var reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = function (e) {
console.log(e)
// 转换完成,创建一个a标签用于下载
var a = document.createElement('a')
a.download = opts.fileName + '.xls'
a.href = e.target.result
$('body').append(a) // 修复firefox中无法触发click
a.click()
$(a).remove()
}
} else {
// toast.error(this.statusText || '导出excel失败!');
}
}
// 发送ajax请求
xhr.send(formData)
}
function isEmptyObj (obj) {
if (typeof obj === 'object' && obj !== null && !(obj instanceof Array)) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
} else {
return false;
}
};
$(document).on('focus keyup', '.jq_common_input', function (e) {
var event = $.Event('focusing');
event.target = e.target;
$(document).trigger(event);
});