当全局方法包含请求时,每调用一次就会请求一次,相当消耗资源
以下方法实现在同一个组件中,多次调用只请求一次,并将数据缓存在组件实例上
Vue.prototype.$initUserLabel = async function(userCode) {
if (!userCode) {
userCode = ''
}
let label = userCode
const vm = this._self
if (!vm._INIT_USER_LABEL_NAMESPACE_) {
vm._INIT_USER_LABEL_NAMESPACE_ = {
init: false,
data: null,
loaded: false,
cache: {}
}
}
if (!vm._INIT_USER_LABEL_NAMESPACE_.init) {
vm._INIT_USER_LABEL_NAMESPACE_.init = true
getUserList().then(res => {
vm._INIT_USER_LABEL_NAMESPACE_.loaded = true
vm._INIT_USER_LABEL_NAMESPACE_.data = res.data
})
}
return new Promise(resolve => {
const loopLoadData = () => {
if (vm._INIT_USER_LABEL_NAMESPACE_.loaded) {
if (vm._INIT_USER_LABEL_NAMESPACE_.cache[userCode]) {
return resolve(vm._INIT_USER_LABEL_NAMESPACE_.cache[userCode])
}
const temp = vm._INIT_USER_LABEL_NAMESPACE_.data.filter(v => (v.workCode).toLocaleUpperCase() === userCode)
if (temp.length > 0) {
// xxxx
// label = xxxx
}
vm._INIT_USER_LABEL_NAMESPACE_.cache[userCode] = label
return resolve(label)
} else {
setTimeout(() => {
loopLoadData()
}, 500)
}
}
loopLoadData()
})
}