🎨 增加 axios 重复请求取消机制

This commit is contained in:
ronger 2022-10-30 16:56:15 +08:00
parent 4a69f4237c
commit 7894d4c3a4
28 changed files with 116 additions and 107 deletions

View File

@ -4,7 +4,7 @@
<header-view/> <header-view/>
</el-header> </el-header>
<el-main> <el-main>
<nuxt :nuxt-child-key="$route.name" keep-alive :keep-alive-props="{max: 16}"/> <nuxt keep-alive/>
</el-main> </el-main>
<el-footer height="5rem"> <el-footer height="5rem">
<footer-view/> <footer-view/>

View File

@ -3,7 +3,7 @@
<el-col v-if="hasPermissions" :span="20"> <el-col v-if="hasPermissions" :span="20">
<el-col :span="4"> <el-col :span="4">
<el-menu <el-menu
:default-active="getActiveMenu" :default-active="activeMenu"
class="el-menu-vertical-demo" class="el-menu-vertical-demo"
@select="handleSelectMenu"> @select="handleSelectMenu">
<template v-for="menu in menus"> <template v-for="menu in menus">
@ -15,7 +15,7 @@
</el-menu> </el-menu>
</el-col> </el-col>
<el-col :span="20"> <el-col :span="20">
<el-tabs v-model="editableTabsValue" type="card" @tab-remove="handleRemoveTab" @tab-click="handleClick"> <el-tabs :value="editableTabsValue" type="card" @tab-remove="handleRemoveTab" @tab-click="handleClick">
<el-tab-pane <el-tab-pane
:key="item.name" :key="item.name"
v-for="(item, index) in editableTabs" v-for="(item, index) in editableTabs"
@ -23,7 +23,7 @@
:name="item.name" :name="item.name"
:closable="item.closable" :closable="item.closable"
> >
<nuxt keep-alive :nuxt-child-key="item.name"/> <nuxt-child keep-alive :keep-alive-props="{exclude: ['login', 'register', 'admin-dashboard'],max: 10}"/>
</el-tab-pane> </el-tab-pane>
</el-tabs> </el-tabs>
</el-col> </el-col>
@ -42,6 +42,7 @@
<script> <script>
import _ from 'lodash' import _ from 'lodash'
import {mapState} from 'vuex';
export default { export default {
name: "Admin", name: "Admin",
@ -130,23 +131,18 @@ export default {
} }
}, },
computed: { computed: {
...mapState({
editableTabs() { editableTabs() {
return this.$store.state.admin.tabs; return this.$store.state.admin.tabs;
}, },
editableTabsValue: { editableTabsValue() {
get() {
return this.$store.state.admin.activeTab; return this.$store.state.admin.activeTab;
}, },
set(value) { activeMenu: state => state.activeMenu,
this.$store.commit('admin/updateActiveTab', value);
}
},
getActiveMenu() {
return this.$store.state.activeMenu;
},
hasPermissions() { hasPermissions() {
return this.$auth.hasScope('admin') || this.$auth.hasScope('blog_admin'); return this.$auth.hasScope('admin') || this.$auth.hasScope('blog_admin');
} }
})
}, },
methods: { methods: {
handleRemoveTab(targetName) { handleRemoveTab(targetName) {
@ -162,35 +158,13 @@ export default {
} }
}); });
} }
this.$store.commit('admin/updateActiveTab', activeName);
this.$store.commit('admin/updateTags', tabs.filter(tab => tab.name !== targetName)) this.$store.commit('admin/updateTags', tabs.filter(tab => tab.name !== targetName))
this.$router.push({ this.handleSelectMenu(activeName)
name: activeName,
params: {
reset: '0'
}
})
}, },
handleClick(item) { handleClick(item) {
let _ts = this this.handleSelectMenu(item.name)
this.$store.commit('admin/updateActiveTab', item.name);
let result = _.findIndex(_ts.editableTabs, function (tab) {
return tab.name === item.name;
})
if (result === -1) {
let index = _.findIndex(_ts.menus, function (menu) {
return menu.name === item.name;
})
_ts.$store.commit('admin/pushTags', _ts.menus[index])
}
_ts.$router.push({
name: item.name,
params: {
reset: '0'
}
})
}, },
handleSelectTab(item) { handleSelectTab(item) {
let _ts = this let _ts = this
@ -221,6 +195,9 @@ export default {
_ts.handleSelectTab(item) _ts.handleSelectTab(item)
} }
} }
},
mounted() {
this.handleSelectMenu(this.$route.name)
} }
} }
</script> </script>

View File

@ -204,9 +204,6 @@ export default {
openLink(link) { openLink(link) {
window.open(link); window.open(link);
} }
},
mounted() {
this.$store.commit("setActiveMenu", "admin-articles");
} }
} }
</script> </script>

View File

@ -147,9 +147,6 @@ export default {
endDate: endDate endDate: endDate
}) })
} }
},
mounted() {
this.$store.commit("setActiveMenu", "admin-bank-accounts");
} }
} }
</script> </script>

View File

@ -157,9 +157,6 @@ export default {
} }
}) })
} }
},
mounted() {
this.$store.commit("setActiveMenu", "admin-banks");
} }
} }
</script> </script>

View File

@ -150,9 +150,6 @@ export default {
}) })
}, },
toggleStatus() {} toggleStatus() {}
},
mounted() {
this.$store.commit("setActiveMenu", "admin-comments");
} }
} }
</script> </script>

View File

@ -151,9 +151,6 @@ export default {
} }
}) })
} }
},
mounted() {
this.$store.commit("setActiveMenu", "admin-currency-rules");
} }
} }
</script> </script>

View File

@ -592,9 +592,11 @@ export default {
}, },
}, },
mounted() { mounted() {
this.$store.commit("setActiveMenu", "admin-dashboard"); let _ts = this
this.initLastThirtyDaysCharts(this.lastThirtyDays) Vue.nextTick(() => {
this.initHistoryCharts(this.history) _ts.initLastThirtyDaysCharts(_ts.lastThirtyDays)
_ts.initHistoryCharts(_ts.history)
})
} }
} }
</script> </script>

View File

@ -156,9 +156,6 @@ export default {
}) })
}, },
handleEdit(index ,row) {} handleEdit(index ,row) {}
},
mounted() {
this.$store.commit("setActiveMenu", "admin-products");
} }
} }
</script> </script>

View File

@ -346,7 +346,6 @@ export default {
}).then(() => { }).then(() => {
next(); next();
}).catch(() => { }).catch(() => {
_ts.$store.commit("setActiveMenu", "admin-tag-post");
return false return false
}); });
} else { } else {
@ -369,7 +368,6 @@ export default {
return '关闭提示'; return '关闭提示';
}); });
let _ts = this; let _ts = this;
_ts.$store.commit('setActiveMenu', 'admin-tag-post');
_ts.$axios.$get('/api/upload/simple/token').then(function (res) { _ts.$axios.$get('/api/upload/simple/token').then(function (res) {
if (res) { if (res) {
_ts.$store.commit('setUploadHeaders', res.uploadToken); _ts.$store.commit('setUploadHeaders', res.uploadToken);

View File

@ -104,9 +104,6 @@
path: '/admin/tag/post/' + id path: '/admin/tag/post/' + id
}) })
} }
},
mounted() {
this.$store.commit("setActiveMenu", "admin-tags");
} }
} }
</script> </script>

View File

@ -351,7 +351,6 @@ export default {
}).then(() => { }).then(() => {
next(); next();
}).catch(() => { }).catch(() => {
_ts.$store.commit("setActiveMenu", "admin-topic-post");
return false return false
}); });
} else { } else {
@ -374,7 +373,6 @@ export default {
return '关闭提示'; return '关闭提示';
}); });
let _ts = this; let _ts = this;
_ts.$store.commit("setActiveMenu", "admin-topic-post");
_ts.$axios.$get('/api/upload/simple/token').then(function (res) { _ts.$axios.$get('/api/upload/simple/token').then(function (res) {
if (res) { if (res) {
_ts.$store.commit('setUploadHeaders', res.uploadToken); _ts.$store.commit('setUploadHeaders', res.uploadToken);

View File

@ -65,9 +65,6 @@
path: '/admin/topic/post' path: '/admin/topic/post'
}) })
} }
},
mounted() {
this.$store.commit("setActiveMenu", "admin-topics");
} }
} }
</script> </script>

View File

@ -227,9 +227,6 @@ export default {
getUserPath(nickname) { getUserPath(nickname) {
return `/user/${nickname}` return `/user/${nickname}`
} }
},
mounted() {
this.$store.commit("setActiveMenu", "admin-users");
} }
} }
</script> </script>

View File

@ -63,7 +63,8 @@ import {mapState} from 'vuex';
export default { export default {
name: "answer", name: "answer",
middleware: 'auth', middleware: 'auth',
fetch({store, params, error}) { fetch() {
let {store, params, error} = this.$nuxt.context
return Promise.all([ return Promise.all([
store store
.dispatch('answer/fetchDetail', params) .dispatch('answer/fetchDetail', params)

View File

@ -70,7 +70,8 @@
} }
return params.article_id && !isNaN(Number(params.article_id)) return params.article_id && !isNaN(Number(params.article_id))
}, },
fetch({store, params, error}) { fetch() {
let {store, params, error} = this.$nuxt.context
return Promise.all([ return Promise.all([
store.dispatch('article/fetchPostDetail', params) store.dispatch('article/fetchPostDetail', params)
.catch(err => error({statusCode: 404})) .catch(err => error({statusCode: 404}))

View File

@ -75,7 +75,8 @@
validate({params, store}) { validate({params, store}) {
return params.draft_id && !isNaN(Number(params.draft_id)) return params.draft_id && !isNaN(Number(params.draft_id))
}, },
fetch({store, params, error}) { fetch() {
let {store, params, error} = this.$nuxt.context
return Promise.all([ return Promise.all([
store store
.dispatch('draft/fetchDetail', params) .dispatch('draft/fetchDetail', params)

View File

@ -19,8 +19,10 @@ export default {
]) ])
}, },
watch: { watch: {
'$route.query': function () { '$route'(to, from) {
this.$store.dispatch('article/fetchList', {page: this.$route.query.page || 1}) if (from.query.page && to.query.page) {
this.$router.go()
}
} }
}, },
components: { components: {

View File

@ -154,8 +154,11 @@ export default {
} }
}, },
mounted() { mounted() {
this.$store.commit("setActiveMenu", "open-data"); let _ts = this
this.initLastThirtyDaysCharts(this.lastThirtyDays) _ts.$store.commit("setActiveMenu", "open-data");
Vue.nextTick(() => {
_ts.initLastThirtyDaysCharts(_ts.lastThirtyDays)
})
} }
} }
</script> </script>

View File

@ -60,7 +60,8 @@ export default {
validate({params, store}) { validate({params, store}) {
return params.portfolio_id && !isNaN(Number(params.portfolio_id)) return params.portfolio_id && !isNaN(Number(params.portfolio_id))
}, },
fetch({store, params, query, error}) { fetch() {
let {store, params, query, error} = this.$nuxt.context
params.page = query.page || 1 params.page = query.page || 1
return Promise.all([ return Promise.all([
store store
@ -70,11 +71,10 @@ export default {
]) ])
}, },
watch: { watch: {
'$route.query': function () { '$route'(to, from) {
this.$store.dispatch('portfolio/fetchArticleList', { if (from.query.page && to.query.page) {
page: this.$route.query.page || 1, this.$router.go()
portfolio_id: this.routePortfolioId }
})
} }
}, },
computed: { computed: {

View File

@ -66,7 +66,8 @@
validate({params, store}) { validate({params, store}) {
return params.portfolio_id && !isNaN(Number(params.portfolio_id)) return params.portfolio_id && !isNaN(Number(params.portfolio_id))
}, },
fetch({store, params, error}) { fetch() {
let {store, params, error} = this.$nuxt.context
return Promise.all([ return Promise.all([
store store
.dispatch('portfolio/fetchDetail', params) .dispatch('portfolio/fetchDetail', params)

View File

@ -31,7 +31,8 @@
validate({params, store}) { validate({params, store}) {
return params.portfolio_id && !isNaN(Number(params.portfolio_id)) return params.portfolio_id && !isNaN(Number(params.portfolio_id))
}, },
fetch({store, params, error}) { fetch() {
let {store, params, error} = this.$nuxt.context
return Promise.all([ return Promise.all([
store store
.dispatch('portfolio/fetchUnBindArticleList', params) .dispatch('portfolio/fetchUnBindArticleList', params)

View File

@ -25,8 +25,10 @@ export default {
]) ])
}, },
watch: { watch: {
'$route.query': function () { '$route'(to, from) {
this.$store.dispatch('portfolio/fetchList', {page: this.$route.query.page || 1}) if (from.query.page && to.query.page) {
this.$router.go()
}
} }
}, },
computed: { computed: {

View File

@ -24,7 +24,8 @@ export default {
validate({params, store}) { validate({params, store}) {
return params.product_id && !isNaN(Number(params.product_id)) return params.product_id && !isNaN(Number(params.product_id))
}, },
fetch({store, params, error}) { fetch() {
let {store, params, error} = this.$nuxt.context
return Promise.all([ return Promise.all([
store store
.dispatch('product/fetchDetail', params) .dispatch('product/fetchDetail', params)

View File

@ -22,8 +22,10 @@ export default {
]) ])
}, },
watch: { watch: {
'$route.query': function () { '$route'(to, from) {
this.$store.dispatch('product/fetchList', {page: this.$route.query.page || 1}) if (from.query.page && to.query.page) {
this.$router.go()
}
} }
}, },
computed: { computed: {

View File

@ -43,7 +43,8 @@ import { mapState } from 'vuex';
export default { export default {
name: "currency", name: "currency",
fetch({store, params, error}) { fetch() {
let {store, params, error} = this.$nuxt.context
return Promise.all([ return Promise.all([
store store
.dispatch('rule/fetchCurrencyRules', params) .dispatch('rule/fetchCurrencyRules', params)

View File

@ -30,12 +30,10 @@ export default {
]) ])
}, },
watch: { watch: {
'$route.query': function () { '$route'(to, from) {
let _ts = this if (from.query.page && to.query.page) {
_ts.$store.dispatch('article/fetchList', { this.$router.go()
topic_uri: _ts.defaultParams.topic_uri, }
page: _ts.defaultParams.page || 1
})
} }
}, },
computed: { computed: {

View File

@ -1,14 +1,54 @@
import {Message} from 'element-ui' import {Message} from 'element-ui'
export default function ({app, $axios, store, redirect}) { export default function ({app, $axios, store, redirect}) {
function generateReqKey(config) {
const { method, url, params, data } = config;
return [method, url, JSON.stringify(params), JSON.stringify(data)].join("&");
}
const pendingRequest = new Map();
function addPendingRequest(config) {
const requestKey = generateReqKey(config);
config.cancelToken = config.cancelToken || new $axios.CancelToken((cancel) => {
if (!pendingRequest.has(requestKey)) {
pendingRequest.set(requestKey, cancel);
}
});
}
function removePendingRequest(config) {
const requestKey = generateReqKey(config);
if (pendingRequest.has(requestKey)) {
const cancelToken = pendingRequest.get(requestKey);
cancelToken(requestKey);
pendingRequest.delete(requestKey);
}
}
$axios.onRequest(config => { $axios.onRequest(config => {
let fingerprint = store.state.fingerprint; let fingerprint = store.state.fingerprint;
if (fingerprint) { if (fingerprint) {
config.headers['fingerprint'] = fingerprint config.headers['fingerprint'] = fingerprint
} }
}) })
$axios.interceptors.request.use(
function (config) {
// 检查是否存在重复请求,若存在则取消已发的请求
removePendingRequest(config);
// 把当前请求信息添加到pendingRequest对象中
addPendingRequest(config);
return config;
},
(error) => {
return Promise.reject(error);
}
);
$axios.onResponse(response => { $axios.onResponse(response => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
removePendingRequest(response.config);
//返回数据逻辑处理 比如error_code错误处理 //返回数据逻辑处理 比如error_code错误处理
let message; let message;
if (typeof (response.data.data) !== 'undefined') { if (typeof (response.data.data) !== 'undefined') {
@ -36,11 +76,18 @@ export default function ({app, $axios, store, redirect}) {
}); });
$axios.onError(error => { $axios.onError(error => {
removePendingRequest(error.config || {}); // 从pendingRequest对象中移除请求
if ($axios.isCancel(error)) {
// console.log("已取消的重复请求:" + error.message);
} else {
// 添加异常处理
const code = parseInt(error.response && error.response.status) const code = parseInt(error.response && error.response.status)
if (code === 400) { if (code === 400) {
redirect('/400'); redirect('/400');
} else { } else {
console.log(error.data); console.log(error.data);
} }
}
}) })
} }