vue中封装的常用方法(全部干货)

引言:

在我们要经常使用一些工具函数的时候,如果每次用到都得定义或者引入是不是很麻烦,封装好一个全局的吧公共方法十分必要,这将会大大节省工作量,而且收集的多了以后也能用的到!

正文内容

1.获取时间(一般时间选择器默认时间用到)

//获取当前时间,day为number,getDay(-1):昨天的日期;getDay(0):今天的日期;getDay(1):明天的日期;
getDay(day) {
let today = new Date(),
targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
today.setTime(targetday_milliseconds);
let tYear = today.getFullYear(),
tMonth = today.getMonth(),
tDate = today.getDate(),
tHour = today.getHours(),
tMinute = today.getMinutes(),
tSeconds = today.getSeconds();
tMonth = this.doHandleMonth(tMonth + 1);
tDate = this.doHandleMonth(tDate);
tHour = this.doHandleMonth(tHour);
tMinute = this.doHandleMonth(tMinute);
tSeconds = this.doHandleMonth(tSeconds);
return tYear + '-' + tMonth + '-' + tDate + ' ' + tHour + ':' + tMinute + ':' + tSeconds;
},

2.判断数据是否是json

//判断数据源是不是json数据
isJsonString(str) {
try {
if (typeof JSON.parse(str) == 'object') {
return true;
}
} catch (e) {
console.log('e', e);
}
return false;
},

3.获取指定位置的天气信息:

//获取天气信息
getWeather() {
axios
.get('https://geoapi.qweather.com/v2/city/lookup', {
params: {
location: '杭州市',
key: '',
_t: new Date().getTime()
},
})
.then(({ data: res }) => {
// console.log(res);
if (res.code != 200) {
return this.$message.error('获取地理位置定位ID(locationID)失败');
}
if (res.location.length > 0) {
axios
.get('https://devapi.qweather.com/v7/weather/now', {
params: {
location: res.location[0].id,
key: '',
_t: new Date().getTime()
},
})
.then(({ data: res1 }) => {
// console.log('res1', res1);
if (res1.status != 0) {
return this.$message.error('获取天气信息失败');
}
this.$set(this.weatherInfo, 'wea', res1.now.text);
this.$set(this.weatherInfo, 'tem', res1.now.temp);
this.$set(this.weatherInfo, 'wea_img', res1.fxLink);
})
.catch((error) => {
console.log(error);
return false;
});
} else {
return this.$message.error('无法获取地理位置定位ID(locationID)');
}
})
.catch((e) => {
console.log(e);
return false;
});
},

4.判断浏览器类型

/**
* 判断浏览器的类型
*/
export function browserType() {
var userAgent = navigator.userAgent.toLowerCase();
var testCenter = {
ie: function isIE() { //ie?
if (!!window.ActiveXObject || "ActiveXObject" in window)
return true;
else
return false;
},
edge: () => {
return /dge/.test(userAgent)
},
chrome: () => {
return /chrome/.test(userAgent)
},
safari: () => {
return /safari/.test(userAgent) && !(/chrome/.test(userAgent))
},
opera: () => {
return /opera/.test(userAgent)
},
msie: () => {
return /msie/.test(userAgent) && !/opera/.test(userAgent)
},
mozilla: () => {
return /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
}
};
var browserObj = {};
for (var k in testCenter) {
var result = testCenter[k]();
var version = (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1];
if (result) {
browserObj.browser = k;
browserObj.version = version;
return browserObj;
}
}
}

5.判断object类型

//判断Object数据类型
export function isType(obj) {
var type = Object.prototype.toString.call(obj);
if (type == '[object Array]') {
return 'Array';
} else if (type == '[object Object]') {
return "Object"
} else {
return 'param is no object type';
}
}

6.全局时间格式封装

export function getSystemDate(param, dateVal) {
let systemDate = dateVal ? new Date(dateVal) : new Date(),
year = systemDate.getFullYear(),
month = systemDate.getMonth() + 1,
date = systemDate.getDate(),
hours = systemDate.getHours(),
minutes = systemDate.getMinutes(),
seconds = systemDate.getDate(),
milliseconds = systemDate.getMilliseconds();
month = month < 10 ? '0' + month : month;
date = date < 10 ? '0' + date : date;
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
if (param == 0) {
return year + '-' + month + '-' + date;
} else if (param == 1) {
return year + '-' + month + '-' + date + " " + hours + ":" + minutes + ":" + seconds;
} else if (param == 2) {
return year + '-' + month + '-' + date + " " + hours + ":" + minutes + ":" + seconds + '.' + milliseconds;
} else if (param == 3) {
return year + '-' + month;
} else if (param == 4) {
return year
}
}

7.判断对象里面是否为空

const isEmpty = (obj) => {
for(let key in obj){
return false
}
return true
};

isEmpty({}); //true
//这里你记得分两次打印,return false 后面都不走了
isEmpty({csdn: '尔嵘'}); // false

8.百度地图坐标和腾讯地图坐标互转

/**
* 坐标转换,百度地图坐标转换成腾讯地图坐标
* lng 腾讯经度(pointy)
* lat 腾讯纬度(pointx)
* 经度>纬度
*/
bMapToQQMap(lng, lat) {
if (lng == null || lng == '' || lat == null || lat == '') return [lng, lat];
var x_pi = 3.14159265358979324;
var x = parseFloat(lng) - 0.0065;
var y = parseFloat(lat) - 0.006;
var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
var lng = (z * Math.cos(theta)).toFixed(7);
var lat = (z * Math.sin(theta)).toFixed(7);
return [lng, lat];
},

/**
* 坐标转换,腾讯地图转换成百度地图坐标
* lng 腾讯经度(pointy)
* lat 腾讯纬度(pointx)
* 经度>纬度
*/
qqMapToBMap(lng, lat) {
if (lng == null || lng == '' || lat == null || lat == '') return [lng, lat];
var x_pi = 3.14159265358979324;
var x = parseFloat(lng);
var y = parseFloat(lat);
var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
var lng = (z * Math.cos(theta) + 0.0065).toFixed(5);
var lat = (z * Math.sin(theta) + 0.006).toFixed(5);
return [lng, lat];
},

9.根据日期(YYYY-MM-DD)获取星期几

export function getWeekByDate(dateString) {
var date;
if (!dateString) {
date = new Date();
} else {
var dateArray = dateString.split("-");
date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
}
//var weeks = new Array("日", "一", "二", "三", "四", "五", "六");
//return "星期" + weeks[date.getDay()];
return "星期" + "日一二三四五六".charAt(date.getDay());
}

10.时间戳(13位)转时间格式:

//时间戳转化成时间格式
export function timeFormat(timestamp) {
//timestamp是整数,否则要parseInt转换,不会出现少个0的情况
//如果timestamp是10位数的需要 timestamp* 1000
var time = new Date(timestamp);
var year = time.getFullYear();
var month = time.getMonth() + 1;
var date = time.getDate();
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
month = month < 10 ? '0' + month : month;
date = date < 10 ? '0' + date : date;
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;

return year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
}

11.数组对象指定键值求和:

// 数组对象求和
export function countTotal(arr, keyName) {
let $total = 0;
$total = arr.reduce(function(total, currentValue, currentIndex, arr) {
return currentValue[keyName] ? (total + Number(currentValue[keyName])) : total;
}, 0);
return $total;
}

12.获取百分数

// 数组对象求和
export function countTotal(arr, keyName) {
let sum = 0;
sum = arr.reduce(function(total, currentValue, currentIndex, arr) {
return currentValue[keyName] ? (total + Number(currentValue[keyName])) : total;
}, 0);
return sum;
}

13.格式化时间(小程序中安卓时间格式转成苹果的格式:-与/)

function formatNumber(n) {
const str = n.toString()
return str[1] ? str : `0${str}`
}

export function formatTime(date) {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()

const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()

const t1 = [year, month, day].map(formatNumber).join('/')
const t2 = [hour, minute, second].map(formatNumber).join(':')

return `${t1} ${t2}`
}

总结

“学而时习之,不亦乐乎?”,学习的时候也要总结,加深自己的理解,祝大家都能早日成为大佬!

© 版权声明

相关文章