You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何以同名参数传递含键值对的字符串数组作为查询参数?

实现包含键值对数组的查询参数拼接

你可以通过遍历参数对象并针对性处理不同类型参数的方式实现需求,以下是两种可行的方案:

方案一:手动拼接查询字符串

直接遍历参数对象的键值对,区分普通参数和数组参数分别构建查询片段,同时对特殊字符做URL编码避免格式错误:

function buildQueryParams(params) {
  const queryParts = [];
  for (const [key, value] of Object.entries(params)) {
    if (Array.isArray(value)) {
      // 处理sequence这类数组参数
      value.forEach(item => {
        // 取出数组项中的唯一键值对(适配示例中每个对象仅一个键的场景)
        const [itemKey, itemValue] = Object.entries(item)[0];
        // 对各部分进行URL编码,防止特殊字符破坏结构
        const encodedKey = encodeURIComponent(key);
        const encodedItemKey = encodeURIComponent(itemKey);
        const encodedItemValue = encodeURIComponent(itemValue);
        queryParts.push(`${encodedKey}=${encodedItemKey}=${encodedItemValue}`);
      });
    } else {
      // 处理普通参数(如id、limit)
      const encodedKey = encodeURIComponent(key);
      const encodedValue = encodeURIComponent(value);
      queryParts.push(`${encodedKey}=${encodedValue}`);
    }
  }
  return queryParts.join('&');
}

// 使用示例
const params = {
  id: '002',
  sequence: [{ s1: 'a' }, { s2: 'b' }, { s3: 'c' }],
  limit: 3
};

const baseUrl = 'https://localhost:3000';
const fullUrl = `${baseUrl}?${buildQueryParams(params)}`;
console.log(fullUrl);

方案二:使用URLSearchParams API

利用浏览器原生的URLSearchParams管理查询参数,它会自动处理参数拼接逻辑,代码更简洁:

function buildQueryParams(params) {
  const searchParams = new URLSearchParams();
  for (const [key, value] of Object.entries(params)) {
    if (Array.isArray(value)) {
      value.forEach(item => {
        const [itemKey, itemValue] = Object.entries(item)[0];
        // 手动编码键值对部分,避免特殊字符干扰
        const paramValue = `${encodeURIComponent(itemKey)}=${encodeURIComponent(itemValue)}`;
        searchParams.append(key, paramValue);
      });
    } else {
      searchParams.append(key, value);
    }
  }
  return searchParams.toString();
}

// 使用示例同方案一
const params = {
  id: '002',
  sequence: [{ s1: 'a' }, { s2: 'b' }, { s3: 'c' }],
  limit: 3
};

const baseUrl = 'https://localhost:3000';
const fullUrl = `${baseUrl}?${buildQueryParams(params)}`;
console.log(fullUrl);

注意事项

  • 必须用encodeURIComponent编码参数的键和值,防止&、=、空格等特殊字符导致URL解析失败。
  • 如果数组项中存在多个键值对(而非示例中的单个),需要调整代码遍历数组项的所有键值对,生成对应查询参数。

内容的提问来源于stack exchange,提问作者user0999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 00:48:38