🎨 增加 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/>
</el-header>
<el-main>
<nuxt :nuxt-child-key="$route.name" keep-alive :keep-alive-props="{max: 16}"/>
<nuxt keep-alive/>
</el-main>
<el-footer height="5rem">
<footer-view/>

View File

@ -3,7 +3,7 @@
<el-col v-if="hasPermissions" :span="20">
<el-col :span="4">
<el-menu
:default-active="getActiveMenu"
:default-active="activeMenu"
class="el-menu-vertical-demo"
@select="handleSelectMenu">
<template v-for="menu in menus">
@ -15,7 +15,7 @@
</el-menu>
</el-col>
<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
:key="item.name"
v-for="(item, index) in editableTabs"
@ -23,7 +23,7 @@
:name="item.name"
: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-tabs>
</el-col>
@ -42,6 +42,7 @@
<script>
import _ from 'lodash'
import {mapState} from 'vuex';
export default {
name: "Admin",
@ -130,23 +131,18 @@ export default {
}
},
computed: {
editableTabs() {
return this.$store.state.admin.tabs;
},
editableTabsValue: {
get() {
...mapState({
editableTabs() {
return this.$store.state.admin.tabs;
},
editableTabsValue() {
return this.$store.state.admin.activeTab;
},
set(value) {
this.$store.commit('admin/updateActiveTab', value);
activeMenu: state => state.activeMenu,
hasPermissions() {
return this.$auth.hasScope('admin') || this.$auth.hasScope('blog_admin');
}
},
getActiveMenu() {
return this.$store.state.activeMenu;
},
hasPermissions() {
return this.$auth.hasScope('admin') || this.$auth.hasScope('blog_admin');
}
})
},
methods: {
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.$router.push({
name: activeName,
params: {
reset: '0'
}
})
this.handleSelectMenu(activeName)
},
handleClick(item) {
let _ts = this
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'
}
})
this.handleSelectMenu(item.name)
},
handleSelectTab(item) {
let _ts = this
@ -221,6 +195,9 @@ export default {
_ts.handleSelectTab(item)
}
}
},
mounted() {
this.handleSelectMenu(this.$route.name)
}
}
</script>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -60,7 +60,8 @@ export default {
validate({params, store}) {
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
return Promise.all([
store
@ -70,11 +71,10 @@ export default {
])
},
watch: {
'$route.query': function () {
this.$store.dispatch('portfolio/fetchArticleList', {
page: this.$route.query.page || 1,
portfolio_id: this.routePortfolioId
})
'$route'(to, from) {
if (from.query.page && to.query.page) {
this.$router.go()
}
}
},
computed: {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,54 @@
import {Message} from 'element-ui'
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 => {
let fingerprint = store.state.fingerprint;
if (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 => {
return new Promise((resolve, reject) => {
removePendingRequest(response.config);
//返回数据逻辑处理 比如error_code错误处理
let message;
if (typeof (response.data.data) !== 'undefined') {
@ -36,11 +76,18 @@ export default function ({app, $axios, store, redirect}) {
});
$axios.onError(error => {
const code = parseInt(error.response && error.response.status)
if (code === 400) {
redirect('/400');
removePendingRequest(error.config || {}); // 从pendingRequest对象中移除请求
if ($axios.isCancel(error)) {
// console.log("已取消的重复请求:" + error.message);
} else {
console.log(error.data);
// 添加异常处理
const code = parseInt(error.response && error.response.status)
if (code === 400) {
redirect('/400');
} else {
console.log(error.data);
}
}
})
}