推荐 防抖+全局请求Loading,能够拦截99%的重复点击场景
防抖:
<script>
import { debounce } from '@/utils/throttle-debounce'
export default {
data() {
return {
// maybe有更好的声明位置
submitForm: debounce(500, this.submitFn)
}
},
methods: {
submitFn(formName) {
this.$refs[formName].validate(async (valid) => {
if (!valid) {
this.$message.warning(this.$store.state.app.checkMsg)
return false
}
let params = {
dtoList: this.ruleForm.dtoList
}
const requestFn = addList
const res = await requestFn(params)
if (res.code != 0) {
return
}
this.$message.success('操作成功!')
this.openDialogPromise.resolve()
this.closeDialog()
})
}
}
}
</script>
全局请求Loading
http.js
import axios from 'axios'
import { Message, Loading } from 'element-ui'
import router from '@/router'
//loading对象
let loadingObj = ''
//当前正在请求的数量
let needLoadingRequestCount = 0
//显示loading
function showLoading(target) {
if (needLoadingRequestCount === 0) {
loadingObj = Loading.service({
lock: true,
background: 'rgba(255, 255, 255, 0.8)',
target: target || '.app-main'
})
}
needLoadingRequestCount++
}
//隐藏loading
function hideLoading() {
needLoadingRequestCount--
needLoadingRequestCount = Math.max(needLoadingRequestCount, 0) //做个保护
if (needLoadingRequestCount === 0 && loadingObj) {
loadingObj.close()
loadingObj = null
}
}
// create an axios instance
const service = axios.create({
baseURL: '',
withCredentials: true,
timeout: 30000,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Application-Token': '',
projectId: ''
}
})
/* 请求前拦截器 */
service.interceptors.request.use(
(config) => {
let customConfig = config['config']
if (!customConfig.notLoading) {
showLoading(customConfig.loadingTarget)
}
return config
},
(error) => {
hideLoading()
return Promise.reject(error.request)
}
)
/* http响应拦截器 */
service.interceptors.response.use(
(response) => {
const res = response.data
if (response.config['config'].notLoading !== true) {
hideLoading()
}
return res
},
(error) => {
hideLoading()
return Promise.reject(error.message)
}
)