【无标题】页面切换继续保留状态请求
// 在 store.js 文件中
import Vue from ‘vue’;
import Vuex from ‘vuex’;
import axios from ‘axios’;
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
taskId: null,
executionStatus: ‘执行中’,
intervalId: null,
},
mutations: {
setTaskId(state, taskId) {
state.taskId = taskId;
},
updateExecutionStatus(state, status) {
state.executionStatus = status;
},
setIntervalId(state, intervalId) {
state.intervalId = intervalId;
},
clearIntervalId(state) {
clearInterval(state.intervalId);
state.intervalId = null;
},
},
actions: {
fetchInitialData({ commit }) {
axios.get(‘第一个接口A的URL’)
.then(response => {
const id = response.data.id;
commit(‘setTaskId’, id);
commit(‘updateExecutionStatus’, ‘执行中’);
this.dispatch(‘fetchExecutionStatus’, id);
})
.catch(error => {
console.error(error);
});
},
fetchExecutionStatus({ commit }, taskId) {
const intervalId = setInterval(() => {
axios.get(第二个接口B的URL?id=${taskId}
)
.then(response => {
const status = response.data.status;
if (status === ‘执行完成’) {
commit(‘updateExecutionStatus’, status);
commit(‘clearIntervalId’);
// 执行完成后的操作
}
})
.catch(error => {
console.error(error);
});
}, 3000);
commit(‘setIntervalId’, intervalId);
},
},
});
export default store;
执行状态: {{ executionStatus }}
这个示例中,我们将任务的状态(任务ID、执行状态、定时器ID等)存储在Vuex的状态中。通过mutations来修改状态,通过actions来分发异步操作。当页面切换回来时,Vuex store中的状态会被保留,因此你可以继续从中获取并处理任务状态。