Nuxt 3 fatch发起get请求时添加了new Date()作为参数,参数中间变成了+号连接,怎么让它用%连接
时间: 2024-11-20 09:34:02 浏览: 33
在Nuxt.js v3中,如果你想要在GET请求中添加日期参数并保持其格式为百分号分隔(`%Y-%m-%d`),而不是加号连接,你需要修改fetch函数中的URL构建部分。通常,你可以通过JavaScript的字符串模板或者直接操作URL来完成这个转换。
例如,假设你有一个名为`getSomeData`的fetch函数,它原本像这样:
```javascript
export default {
async fetch({ params }) {
const currentDate = new Date();
const formattedDate = currentDate.toISOString().split('T')[0]; // 使用toISOString()然后取年月日部分
return this.$axios.get(`/api/data?date=${formattedDate}`);
}
}
```
这里,`currentDate.toISOString().split('T')[0]`会生成类似`2023-04-07`这样的字符串。如果你想改为百分号分隔,可以将`split('T')[0]`替换为`replace(/-/g, '%')`,如下所示:
```javascript
export default {
async fetch({ params }) {
const currentDate = new Date();
const formattedDate = currentDate.toISOString().split('T')[0].replace(/-/g, '%');
return this.$axios.get(`/api/data?date=${encodeURIComponent(formattedDate)}`); // 加入encodeURIComponent处理特殊字符
}
}
```
现在,`formattedDate`将会包含 `%Y-%m-%d`格式的日期。注意我们还对日期字符串进行了encodeURIComponent编码,以防特殊字符导致URL解析错误。
阅读全文
相关推荐


















