业务说明
在app.vue,created中调用了一个同步用户信息的接口,但不希望每个页面刷新都会调用,并限制在页面的调用频率
具体实现
js
/**
* 判断是否应该调用接口 白名单下的直接调用
* @param {String} api_name 接口名字
* @param {String} router_name 当前路由名字
* @param {Array} routers_name 白名单路由名字
* @param {Number} time 过期时间
*
* **/
export function getNeedApi(api_name = '', router_name, routers_name = [], time = 5 * 60 * 1000) {
if (routers_name.includes(router_name)) {
return true
}
let isFlag = false
let now = Date.now()
let needApi = sessionStorage.getItem(`needApi_${api_name}`)
if (needApi) {
needApi = JSON.parse(needApi)
if (needApi.time && now - needApi.time > time) {
isFlag = true
}
} else {
isFlag = true
}
return isFlag
}
/**
* 新增api访问记录
* @param {String} api_name 接口名字
* **/
export function postNeedApi(api_name = '') {
let now = Date.now()
sessionStorage.setItem(`needApi_${api_name}`, JSON.stringify({ time: now }))
}
使用
- getNeedApi先判断是否过期,调用后添加一次postNeedApi
js
post_user_sync() {
if (!this.getNeedApi('post_user_sync', this.routeName)) return
let { email, password } = this.userdata
if (!email || !password) return
let params = {
email,
password,
sync: 'sync',
}
if (
!this.isDev() &&
window.performance &&
this.isObject(window.performance.timing)
) {
let { timing } = window.performance
let arr = [
{
label: '脚本加载时间',
value: timing.domComplete - timing.domInteractive,
},
{
label: '白屏时间',
value: timing.domLoading - timing.fetchStart,
},
{
label: '页面完全加载时间',
value: timing.loadEventStart - timing.navigationStart,
},
]
// 网络情况
let netInfo = {}
if (this.isObject(navigator.connection)) {
let { downlink, effectiveType, rtt } = navigator.connection
netInfo = {
downlink,
effectiveType,
rtt,
}
}
let data = {
load_time: arr,
netInfo,
}
params = {
...params,
...data,
}
}
httpApi.post_user_sync(params).then((res) => {
this.postNeedApi('post_user_sync')
this.setUserData({
user: res.data.data,
})
}).catch((e) => {
console.log('同步用户信息失败', e)
})
},