uView UI组件库http介绍和封装

uni-app项目中,uView是一个非常流行的UI组件库,它内部封装了一个uView-http模块用于网络请求。我们可以在uViewhttp库基础上封装一个通用的请求方法,使其更易于管理和使用。


1. uView http 模块简介

uViewhttp 模块提供了一系列方法来进行网络请求,主要方法如下:

  • setConfig(config):全局配置http请求的默认参数,例如baseURLheader等。
  • request(options):通用的请求方法,支持GETPOST等各种请求方式。
  • get(url, params, config):发起GET请求,params作为查询参数。
  • post(url, params, config):发起POST请求,params作为请求体。
  • put(url, params, config):发起PUT请求。
  • delete(url, params, config):发起DELETE请求。
  • upload(url, options):用于上传文件。
  • custom(options):创建自定义实例,以支持不同的baseURL

2. 封装通用http请求方法

我们可以基于uViewhttp模块封装一个通用的请求方法,具备:

  • 全局配置baseURL、默认header
  • 请求拦截(如:token 处理)
  • 响应拦截(如:错误处理、消息提示)
  • 统一返回数据格式(便于调用时处理)

封装代码

复制代码
// utils/request.js
import Vue from 'vue';
import store from '@/store'; // 假设有 Vuex 进行 token 管理

// uView 的 http 请求库
const http = Vue.prototype.$u.http;

// 配置 http 全局默认参数
http.setConfig((config) => {
    config.baseURL = 'https://api.example.com'; // 你的 API 地址
    config.header = {
        'Content-Type': 'application/json',
    };
    return config;
});

// 请求拦截器
http.interceptor.request = (config) => {
    // 如果 Vuex 存在 token,就在 header 中携带
    const token = store.state.token;
    if (token) {
        config.header['Authorization'] = `Bearer ${token}`;
    }
    return config;
};

// 响应拦截器
http.interceptor.response = (res) => {
    if (res.code === 200) {
        return res.data; // 正常返回数据
    } else {
        // 处理错误
        uni.showToast({
            title: res.msg || '请求错误',
            icon: 'none',
        });
        return Promise.reject(res);
    }
};

// 封装通用请求方法
const request = (url, method = 'GET', data = {}, config = {}) => {
    return new Promise((resolve, reject) => {
        http
            .request({
                url,
                method,
                data,
                ...config,
            })
            .then((res) => {
                resolve(res);
            })
            .catch((err) => {
                reject(err);
            });
    });
};

// 封装 get 请求
const get = (url, params = {}, config = {}) => request(url, 'GET', params, config);

// 封装 post 请求
const post = (url, data = {}, config = {}) => request(url, 'POST', data, config);

// 封装 put 请求
const put = (url, data = {}, config = {}) => request(url, 'PUT', data, config);

// 封装 delete 请求
const del = (url, params = {}, config = {}) => request(url, 'DELETE', params, config);

// 文件上传
const upload = (url, filePath, name = 'file', formData = {}) => {
    return http.upload(url, {
        filePath,
        name,
        formData,
    });
};

export { get, post, put, del, upload };

3. 在 Vue 组件中使用

封装好通用方法后,在组件中可以直接调用,例如:

复制代码
<script>
import { get, post } from '@/utils/request.js';

export default {
    async mounted() {
        try {
            // 发送 GET 请求
            const userData = await get('/user/info');
            console.log('用户信息:', userData);

            // 发送 POST 请求
            const loginRes = await post('/user/login', { username: 'admin', password: '123456' });
            console.log('登录成功:', loginRes);
        } catch (error) {
            console.error('请求出错:', error);
        }
    }
};
</script>

4. uView http 模块各方法的使用

方法 说明 示例
setConfig(config) 设置全局http默认配置 http.setConfig({ baseURL: 'https://api.example.com' });
request(options) 发送通用请求 http.request({ url: '/user', method: 'GET' });
get(url, params, config) 发送GET请求 http.get('/user', { id: 1 });
post(url, params, config) 发送POST请求 http.post('/user', { name: 'Tom' });
put(url, params, config) 发送PUT请求 http.put('/user/1', { name: 'Jack' });
delete(url, params, config) 发送DELETE请求 http.delete('/user/1');
upload(url, options) 文件上传 http.upload('/upload', { filePath, name: 'file' });

5. 总结

通过封装:

  • 减少代码冗余,简化 API 调用方式
  • 统一错误处理 ,避免每个请求都需要 catch
  • 集成 token 处理,提高安全性
  • 支持文件上传,满足多种请求需求

这样封装后,开发时只需 get('/user')post('/login', { username, password }) 就能高效发送请求,代码清晰、易维护。

相关推荐
fakaifa9 小时前
【最新版】CRMEB Pro版v3.4系统源码全开源+PC端+uniapp前端+搭建教程
人工智能·小程序·uni-app·php·crmeb·源码下载·crmebpro
2501_9159184115 小时前
iOS 应用上架全流程实践,从开发内测到正式发布的多工具组合方案
android·ios·小程序·https·uni-app·iphone·webview
梦里寻码1 天前
自行食用 uniapp 多端 手写签名组件
前端·uni-app
知识分享小能手1 天前
Vue3 学习教程,从入门到精通,Axios 在 Vue 3 中的使用指南(37)
前端·javascript·vue.js·学习·typescript·vue·vue3
不如摸鱼去2 天前
Trae 辅助下的 uni-app 跨端小程序工程化开发实践分享
微信小程序·小程序·uni-app·aigc·ai编程
码码哈哈爱分享2 天前
Tauri 框架介绍
css·rust·vue·html
小白_ysf2 天前
uniapp 开发微信小程序,获取经纬度并且转化详细地址(单独封装版本)
微信小程序·uni-app
iOS阿玮2 天前
三年期已满,你的产品不再更新将于90天后下架。
uni-app·app·apple
i紸定i2 天前
解决html-to-image在 ios 上dom里面的图片不显示出来
前端·ios·vue·html·html-to-image
bug总结3 天前
深入理解 uni-app 的 uni.createSelectorQuery()
uni-app