如何通过日期选择器修改API链接末尾的动态年月参数
实现方案
现有代码存在变量名拼写不一致问题:定义的变量为timehsheetUrl,拼接URL时误写为timesleetUrl,请先修正该问题。
步骤1:页面插入年月选择器
使用原生input的month类型即可实现无需额外依赖的年月选择功能:
<input type="month" id="monthPicker" />
步骤2:封装动态请求配置生成函数
将原有硬编码的日期逻辑重构为可接收自定义日期参数的函数,默认仍使用当前年月,不影响原有默认功能:
const timesheetUrl = "API LINK" // 已修正拼写错误 // 入参支持传入自定义日期,默认值为当前日期 function getRequestSettings(targetDate = new Date()) { const year = targetDate.getFullYear() const month = ('0' + (targetDate.getMonth() + 1)).slice(-2) const dateStr = `${year}${month}` return { async: true, crossDomain: true, url: timesheetUrl + dateStr, method: "GET", headers: {} } } // 原有默认请求逻辑可直接调用,和之前效果完全一致 const defaultSettings = getRequestSettings()
步骤3:监听日期选择器变更,动态更新请求
给选择器绑定变更事件,用户选择日期后自动生成新的请求配置:
const monthPicker = document.getElementById('monthPicker') // 初始化选择器默认值为当前年月 const now = new Date() monthPicker.value = `${now.getFullYear()}-${('0' + (now.getMonth() + 1)).slice(-2)}` // 监听选择动作 monthPicker.addEventListener('change', (e) => { // 将选中的YYYY-MM格式值转为日期对象传入生成函数 const selectedDate = new Date(e.target.value) const newRequestSettings = getRequestSettings(selectedDate) // 此处替换为你原有发起请求的逻辑,使用新配置发起请求即可 console.log('新请求URL:', newRequestSettings.url) })
如果你使用的是Element UI、Ant Design等第三方组件库的日期选择器,只要能拿到选中的日期对象或YYYY-MM格式的字符串,传入getRequestSettings函数即可复用全部逻辑。
内容的提问来源于stack exchange,提问作者Gabe
相关产品推荐
相关产品推荐

