在 Vue.js 中实现根据时间动态切换接口参数是一个常见的需求,特别是在需要根据不同时间段获取不同数据的场景下。以下是几种实现方案:
export default {
data() {
return {
currentTime: new Date(),
intervalId: null,
apiParams: {
// 默认参数
type: 'day'
}
}
},
created() {
this.startTimeChecker();
this.fetchData();
},
beforeDestroy() {
this.stopTimeChecker();
},
methods: {
startTimeChecker() {
this.intervalId = setInterval(() => {
this.currentTime = new Date();
this.updateApiParams();
}, 60000); // 每分钟检查一次
},
stopTimeChecker() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
},
updateApiParams() {
const hour = this.currentTime.getHours();
// 根据时间切换参数
if (hour >= 6 && hour < 12) {
this.apiParams.type = 'morning';
} else if (hour >= 12 && hour < 18) {
this.apiParams.type = 'afternoon';
} else {
this.apiParams.type = 'night';
}
// 参数变化时重新获取数据
this.fetchData();
},
async fetchData() {
try {
const response = await axios.get('/api/data', {
params: this.apiParams
});
// 处理数据...
} catch (error) {
console.error('获取数据失败:', error);
}
}
}
}
export default {
data() {
return {
currentTime: new Date(),
intervalId: null
}
},
computed: {
apiParams() {
const hour = this.currentTime.getHours();
if (hour >= 6 && hour < 12) {
return { type: 'morning' };
} else if (hour >= 12 && hour < 18) {
return { type: 'afternoon' };
} else {
return { type: 'night' };
}
}
},
watch: {
apiParams: {
handler(newVal, oldVal) {
if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
this.fetchData();
}
},
deep: true,
immediate: true
}
},
created() {
this.intervalId = setInterval(() => {
this.currentTime = new Date();
}, 60000);
},
beforeDestroy() {
clearInterval(this.intervalId);
},
methods: {
async fetchData() {
// 同上
}
}
}
// store.js
const store = new Vuex.Store({
state: {
currentTime: new Date()
},
mutations: {
updateTime(state) {
state.currentTime = new Date();
}
},
actions: {
startTimeUpdate({ commit }) {
setInterval(() => {
commit('updateTime');
}, 60000);
}
},
getters: {
apiParams: state => {
const hour = state.currentTime.getHours();
// 返回相应的参数对象
}
}
});
// 组件中
export default {
computed: {
...mapGetters(['apiParams'])
},
watch: {
apiParams: {
handler(newVal) {
this.fetchData(newVal);
},
immediate: true
}
},
created() {
this.$store.dispatch('startTimeUpdate');
},
methods: {
async fetchData(params) {
// 使用params获取数据
}
}
}
// 节流和取消请求示例
let cancelToken = null;
methods: {
async fetchData() {
// 取消之前的请求
if (cancelToken) {
cancelToken.cancel('参数已变化,取消之前请求');
}
// 创建新的取消令牌
cancelToken = axios.CancelToken.source();
try {
const response = await axios.get('/api/data', {
params: this.apiParams,
cancelToken: cancelToken.token
});
// 处理数据...
} catch (error) {
if (!axios.isCancel(error)) {
console.error('获取数据失败:', error);
}
}
}
}
选择哪种方案取决于你的应用规模和复杂度。对于简单应用,方案一或二足够;对于大型应用,方案三更合适。