首页 > 其他分享 >vue中封装的常用方法(全部干货)

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

时间:2022-11-04 15:01:23浏览次数:51  
标签:vue return month date 干货 var 封装 lng lat

引言:

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

正文内容

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}`
}

...

总结

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


标签:vue,return,month,date,干货,var,封装,lng,lat
From: https://blog.51cto.com/u_14562672/5821573

相关文章

  • #yyds干货盘点#【愚公系列】2022年11月 微信小程序-icon图标详解
    前言在小程序中经常会用到各种各样的图标,如果这些图标都使用图片的话,将会大大增加小程序打包后的体积,而小程序限制代码最大2MB,分包加载4MB,所以为了缩小体积,我们可以使用图......
  • #yyds干货盘点# 前端歌谣的刷题之路-第一百四十七题-三列布局-浮动
     前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了......
  • #yyds干货盘点# 前端歌谣的刷题之路-第一百四十八题-三列布局-绝对定位
     前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了......
  • Vue超全资源
    这些资源涉及有关VueJS的组件库,示例,项目,工具和文章。UI库和框架UI 组件库是一组(通常)可靠的现成 UI 组件,如按钮、输入、对话框等。它们用作布局的构建基块。由于其模......
  • Vue2 到 Vue3,重学这 5 个常用的 API
    距离Vue3发布已经过去一年多时间了,从Vue2到Vue3是一个不小的升级,包括周边生态等。虽然目前大多数开发者们在使用的仍旧以Vue2为准,但Vue3显然是Vue开发者们未来必须面对的,......
  • vue 金额、千分位、保留几位小数
    最近项目中有需求,千分位,同时重量要保留3位,金额要保留2位,金额对精度要求高,需要保留6位,提供一种同时保留千分位,小数位数随机的方法filters:{/*s:要格式化的数字,n:......
  • vue中的依赖注入provide和inject(简单易懂)
    本文开始,首先我们来看这两个词的意思,provide:提供  inject:注入 用处:父组件可以向其所有子组件传入数据,而“不管子组件层次结构有多深(非父子和父子咱都能传)” 特性......
  • Vue.nextTick核心原理
    相信大家在写vue项目的时候,一定会发现一个神奇的api,Vue.nextTick。为什么说它神奇呢,那是因为在你做某些操作不生效时,将操作写在Vue.nextTick内,就神奇的生效了。那这是什么......
  • 解读Vue3模板编译优化
    今天的文章打算学习下Vue3下的模板编译与Vue2下的差异,以及VDOM下Diff算法的优化。编译入口了解过Vue3的同学肯定知道Vue3引入了新的组合Api,在组件mount阶......
  • 聊聊Vuex原理
    背景Vuex是一个专为Vue.js应用程序开发的状态管理模式。Vuex是专门为Vue.js设计的状态管理库,以利用Vue.js的细粒度数据响应机制来进行高效的状态更新。如果你已......