场景:列表页,可以切换 tab 展示获取对应类型的数据,懒加载,每次请求后拼接到已有列表后面
问题:快速切换,当前列表下会拼接上一个 tab 请求返回的数据
解决:使用 axios 的 cancelToken,发起请求时保存,切换时取消请求
axios 封装
// request
const request = axios.create() request.interceptors.request.use(config => { config.cancelToken = new axios.CancelToken(cancel => { store.addCancelToken(cancel) }) ... }, error => {}) request.interceptors.response.use( response => { ... }, error => { if (error instanceof axios.Cancel) return ... } )
store
// store state: () => { return { cancelTokenList: [], } }, actions: { addCancelToken(cancelToken) { this.cancelTokenList.push(cancelToken) }, deleteCancelToken(index) { this.cancelTokenList.splice(index, 1) }, },
业务
function handleTabChange( ) { store.cancelTokenList.forEach((cancel, index) => { cancel && cancel() store.deleteCancelToken(index) }) getData() }
标签:index,axios,cancel,cancelTokenList,切换,tab,错乱,store From: https://www.cnblogs.com/veinyin/p/17070486.html