每隔多长时间向后台请求一次数据
1、在mounted方法中定义一个定时器,每隔多长时间去触发一下
mounted() {
clearInterval(this.timer);
this.timer = setInterval(() => {
let newTime = new Date().getTime();
store.commit('user/UPDATE_Time', newTime);//在store下面的user模块中,实时的改变的时间
}, setTime * 1000 * 60);
},
destroyed() {
clearInterval(this.timer);
}
2、store文件下的user.js代码
import api from '@/assets/api';
export default {
namespaced: 'user',
state: {
// token信息
token: 'null',
newTime: '',
},
mutations: {
// 更新TOKEN
UPDATE_TOKEN(state, data) {
state.token = data;
},
//可以实时的更新时间
UPDATE_Time(state, data) {
state.newTime = data;
},
},
actions: {},
};
3、在各个页面中去监听时间的变化,当时间有变化的时候,则去向后台发送请求,请求数据‘
computed: {
isFollow() {
return store.state.user.newTime; //需要监听的数据
},
},
watch: {
isFollow(newVal, oldVal) {
//当时间发生变化的时候,isFollow也会随之变化,此时调用请求数据的方法即可
this.reqEquimentDis();
},
},