在 Vue.js 中实现根据时间动态切换接口日期参数可以通过以下几种方式实现:
export default {
data() {
return {
currentDate: this.getCurrentDate(),
intervalId: null
}
},
methods: {
getCurrentDate() {
const now = new Date()
return now.toISOString().split('T')[0] // 格式化为 YYYY-MM-DD
},
fetchData(date) {
// 根据日期参数调用API
axios.get(`/api/data?date=${date}`)
.then(response => {
// 处理数据
})
.catch(error => {
console.error('Error fetching data:', error)
})
},
checkDateChange() {
const newDate = this.getCurrentDate()
if (newDate !== this.currentDate) {
this.currentDate = newDate
this.fetchData(newDate)
}
}
},
mounted() {
// 初始获取数据
this.fetchData(this.currentDate)
// 每分钟检查一次日期是否变化
this.intervalId = setInterval(this.checkDateChange, 60000)
},
beforeDestroy() {
// 组件销毁时清除定时器
clearInterval(this.intervalId)
}
}
export default {
data() {
return {
currentDate: this.getCurrentDate()
}
},
methods: {
getCurrentDate() {
const now = new Date()
return now.toISOString().split('T')[0]
},
fetchData(date) {
// API调用逻辑
},
scheduleDateCheck() {
const newDate = this.getCurrentDate()
if (newDate !== this.currentDate) {
this.currentDate = newDate
this.fetchData(newDate)
}
// 设置下一次检查(在下一个整点分钟)
const now = new Date()
const delay = 60000 - (now.getSeconds() * 1000 + now.getMilliseconds())
setTimeout(this.scheduleDateCheck, delay)
}
},
mounted() {
this.fetchData(this.currentDate)
this.scheduleDateCheck()
}
}
如果你项目中使用 vue-timers 插件:
export default {
data() {
return {
currentDate: this.getCurrentDate()
}
},
methods: {
getCurrentDate() {
return new Date().toISOString().split('T')[0]
},
fetchData(date) {
// API调用逻辑
},
onDateCheck() {
const newDate = this.getCurrentDate()
if (newDate !== this.currentDate) {
this.currentDate = newDate
this.fetchData(newDate)
}
}
},
timers: {
checkDate: { time: 60000, autostart: true, repeat: true, immediate: true }
},
mounted() {
this.fetchData(this.currentDate)
}
}
// worker.js
self.onmessage = function(e) {
if (e.data === 'start') {
setInterval(() => {
const newDate = new Date().toISOString().split('T')[0]
self.postMessage(newDate)
}, 60000)
}
}
// Vue组件
export default {
data() {
return {
currentDate: this.getCurrentDate(),
worker: null
}
},
methods: {
getCurrentDate() {
return new Date().toISOString().split('T')[0]
},
fetchData(date) {
// API调用逻辑
}
},
mounted() {
this.fetchData(this.currentDate)
this.worker = new Worker('./worker.js')
this.worker.postMessage('start')
this.worker.onmessage = (e) => {
if (e.data !== this.currentDate) {
this.currentDate = e.data
this.fetchData(e.data)
}
}
},
beforeDestroy() {
this.worker.terminate()
}
}
以上方法都可以实现根据时间动态切换接口参数的功能,选择哪种取决于你的具体需求和项目架构。