vue3-config

太好了!我们来详细讲解配置(config)。我会用点外卖APP的例子来类比,这样更容易理解。

1. 什么是 config?

config 就像是你点外卖时的订单信息,告诉系统:

  • 你要什么菜(请求什么数据)
  • 送到哪里(请求地址)
  • 有什么特殊要求(请求参数)
  • 怎么包装(请求头)

2. 常见的 config 配置项

2.1 基本配置(外卖订单的基本信息)

复制代码
const config = {
  // 必填项:你要什么(URL)
  url: '/api/user/123',  // 获取用户123的信息
  
  // 选填项:怎么要(方法)
  method: 'get',  // 获取数据(GET就像查看菜单)
                   // 还有:post(下单)、put(修改订单)、delete(取消订单)
  
  // 选填项:送到哪里的总地址(基础URL)
  baseURL: 'https://api.restaurant.com',
  // 最终请求地址 = baseURL + url
  // 例如:https://api.restaurant.com/api/user/123
  
  // 选填项:等多长时间(超时时间)
  timeout: 10000,  // 10秒,超过就认为外卖送不到了
  
  // 选填项:包装要求(请求头)
  headers: {
    'Content-Type': 'application/json',  // 数据格式:JSON
    'X-Custom-Header': 'foobar'          // 自定义要求
  }
}

2.2 带参数的数据配置

复制代码
// GET 请求:查看特定条件的菜单
const config1 = {
  method: 'get',
  url: '/api/dishes',
  params: {  // GET请求用 params,会变成 ?category=chinese&spicy=true
    category: 'chinese',
    spicy: true,
    page: 1,
    limit: 10
  }
}
// 最终URL:/api/dishes?category=chinese&spicy=true&page=1&limit=10

// POST 请求:下单
const config2 = {
  method: 'post',
  url: '/api/orders',
  data: {  // POST请求用 data,放在请求体里
    userId: 123,
    dishes: ['宫保鸡丁', '麻婆豆腐'],
    address: '北京市朝阳区',
    remarks: '不要香菜'
  }
}

// PUT 请求:修改订单
const config3 = {
  method: 'put',
  url: '/api/orders/456',
  data: {
    remarks: '改成微辣'
  }
}

3. 完整的 config 实例

复制代码
// 一个完整的点外卖配置
const orderConfig = {
  // 基本信息
  url: '/v1/orders',
  method: 'post',
  baseURL: 'https://delivery-api.com',
  
  // 请求参数(放在URL里)
  params: {
    timestamp: Date.now()  // 加时间戳防止缓存
  },
  
  // 请求数据(放在请求体里)
  data: {
    userId: 'user_123',
    restaurantId: 'res_456',
    items: [
      { id: 1, name: '红烧肉', quantity: 1, price: 38 },
      { id: 2, name: '米饭', quantity: 2, price: 2 }
    ],
    totalAmount: 42,
    deliveryAddress: '科技园A座',
    paymentMethod: 'wechat'
  },
  
  // 请求头(包装和说明)
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'your_api_key_here',
    'X-Request-ID': 'req_789',  // 请求ID,方便追踪
    'Accept-Language': 'zh-CN'
  },
  
  // 超时设置
  timeout: 30000,  // 30秒超时
  
  // 响应类型
  responseType: 'json',  // 期望返回JSON
  
  // 跨域设置
  withCredentials: true,  // 允许携带cookie(像保存会员信息)
  
  // 验证状态码
  validateStatus: function (status) {
    return status >= 200 && status < 500; // 200-499都认为是有效的
  },
  
  // 请求拦截器(可以在这里设置,也可以在全局设置)
  transformRequest: [
    function (data, headers) {
      // 可以对发送的数据进行转换
      console.log('正在准备发送数据:', data);
      return JSON.stringify(data);
    }
  ],
  
  // 进度事件(上传/下载进度)
  onUploadProgress: function (progressEvent) {
    const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(`上传进度: ${percentCompleted}%`);
  },
  
  onDownloadProgress: function (progressEvent) {
    const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(`下载进度: ${percentCompleted}%`);
  }
};

4. 实际使用示例

4.1 直接在请求中使用 config

复制代码
// 方式1:直接传 config 对象
axios({
  url: '/api/user',
  method: 'get',
  params: { id: 123 }
})

// 方式2:使用别名方法(更简洁)
axios.get('/api/user', {
  params: { id: 123 },
  timeout: 5000
})

axios.post('/api/order', {
  dish: '红烧肉',
  quantity: 2
}, {
  headers: { 'X-Token': 'abc123' },
  timeout: 10000
})

4.2 在拦截器中修改 config

复制代码
// 请求拦截器:统一修改所有请求的 config
axios.interceptors.request.use(config => {
  // 1. 添加 token
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  
  // 2. 统一添加时间戳,防止缓存
  if (config.method === 'get') {
    config.params = {
      ...config.params,
      _t: Date.now()
    };
  }
  
  // 3. 根据环境设置不同的 baseURL
  if (process.env.NODE_ENV === 'development') {
    config.baseURL = 'http://localhost:3000/api';
  } else {
    config.baseURL = 'https://api.production.com';
  }
  
  // 4. 记录请求日志
  console.log(`📤 ${config.method.toUpperCase()} ${config.url}`, config.params || config.data);
  
  return config;
});

4.3 创建 axios 实例并配置

复制代码
// 创建针对特定服务的实例
const apiClient = axios.create({
  baseURL: 'https://api.restaurant.com/v1',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json',
    'X-Client-Version': '1.0.0'
  }
});

// 针对用户服务的实例
const userApi = axios.create({
  baseURL: 'https://api.user.com',
  timeout: 10000
});

// 针对订单服务的实例
const orderApi = axios.create({
  baseURL: 'https://api.order.com',
  timeout: 30000,  // 订单处理可能较慢
  headers: {
    'X-Service-Name': 'order-service'
  }
});

// 使用不同的实例
userApi.get('/profile');      // -> https://api.user.com/profile
orderApi.post('/create', data); // -> https://api.order.com/create

5. 实际场景配置示例

场景1:文件上传

复制代码
const uploadConfig = {
  method: 'post',
  url: '/api/upload',
  data: formData,  // FormData 对象
  headers: {
    'Content-Type': 'multipart/form-data'  // 文件上传必须用这个
  },
  onUploadProgress: (progressEvent) => {
    const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(`上传进度: ${progress}%`);
    // 可以更新UI进度条
    updateProgressBar(progress);
  },
  timeout: 60000  // 文件上传需要更长时间
};

场景2:需要缓存的请求

复制代码
const cachedConfig = {
  method: 'get',
  url: '/api/menu',
  params: { restaurantId: 123 },
  headers: {
    'Cache-Control': 'max-age=300'  // 缓存5分钟
  },
  adapter: 'cache'  // 使用缓存适配器
};

场景3:重试配置

复制代码
const retryConfig = {
  method: 'post',
  url: '/api/payment',
  data: paymentData,
  timeout: 10000,
  retry: 3,  // 重试3次
  retryDelay: 1000  // 每次重试间隔1秒
};

6. 配置的优先级顺序

复制代码
// 配置的优先级(从高到低):
// 1. 请求时传入的配置(最高优先级)
axios.get('/api/user', {
  timeout: 5000  // 这个会覆盖下面的
});

// 2. 实例的默认配置
const instance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10000  // 默认10秒
});

// 3. 全局默认配置(最低优先级)
axios.defaults.timeout = 20000;
axios.defaults.headers.common['Authorization'] = 'default_token';

7. 练习:配置一个完整的订单请求

你来配置一个外卖订单请求:

复制代码
const orderRequest = {
  url: '/orders',
  method: '___',  // 应该填什么?POST/GET/PUT/DELETE?
  baseURL: 'https://food-api.com',
  
  // 用户信息
  headers: {
    'Content-Type': '___',  // JSON格式应该填什么?
    'X-User-Token': 'user_token_123'
  },
  
  // 订单数据
  data: {
    userId: 123,
    items: [
      { name: '鱼香肉丝', price: 28, quantity: 1 },
      { name: '米饭', price: 2, quantity: 2 }
    ],
    address: '科技园B座',
    phone: '13800138000'
  },
  
  // 超时时间(单位:毫秒)
  timeout: ___,
  
  // 期望的响应类型
  responseType: '___'
};

8. 常见问题解答

Q: params 和 data 有什么区别?

  • params : 用于 GET 请求,参数会拼在URL后面 ?key=value
  • data: 用于 POST/PUT 请求,参数放在请求体里

Q: 为什么有时候要设置 withCredentials?

  • 当需要跨域请求并携带 cookie(如 session)时
  • 默认 false,如果需要发送 cookie 就设为 true

Q: responseType 有哪些选项?

  • json (默认) - 自动解析 JSON
  • text - 返回文本
  • blob - 返回 Blob 对象(文件下载)
  • arraybuffer - 返回 ArrayBuffer
  • stream - 返回流

现在你对 config 理解了吗?告诉我:

  1. 哪个配置项你还不清楚?
  2. 你想了解哪个特定的配置场景?
  3. 需要我解释哪个例子?

我们继续!😊

相关推荐
明月_清风39 分钟前
位图与布隆过滤器:海量数据下的"存在性判断"艺术
前端·后端·算法
明月_清风1 小时前
Hash 表从入门到精通:Go 实战与工程细节
前端·后端·算法
非凡ghost2 小时前
AI修图不“造假“,摄影师的出片效率加速器
服务器·前端·人工智能·电脑
2601_951615202 小时前
网页设计模板源码 web前端模板网页源码下载
前端
mmsx2 小时前
osmdroid 地图实战 03|地图的"分层世界":离线方案、图层模型与 Overlay 体系
android·前端
郭邯3 小时前
从零到一:我用 AI 写了个复利计算器,顺便治好了我的"公式恐惧症"
前端
Pointer Pursuit3 小时前
C++11特性(二)
前端·c++·算法
天道kabuto3 小时前
Vue3 升级踩坑:子组件 click 事件为什么会触发两次?
前端
Nayana3 小时前
《Web 到 HarmonyOS》-- Ability、Stage、模块化与路由导航
前端