uni-well

1.0.7 • Public • Published

介绍

初衷

本框架是服务于 uni-app 开发者的小程序框架。由于本人之前参与的项目都是在使用 vue2 进行开发,对 vue3 的生态相对陌生,开发目的是为了拥抱 vue3+vite 的生态,提高开发者的体验和项目性能。

容易上手

uni-well 的使用方式非常简单,您只需要引入然后就能在 uni 对象下使用 uni-well 带给您的所有功能,目前只具有 http 模块($h)以及工具方法模块($a),后续可能会更新 compositionAPI 格式的 UI 组件库以及兼容状态管理的解决方案

PR

通过使用和阅读本框架的源码你可以学到一些封装的基本知识,同时欢迎您对 uni-well 的生态贡献自己的力量。

快速上手

安装

npm i uni-well

使用 uni-well 的模块

因为框架的是功能挂载在全局对象 uni 上的,所以我们只需在 main.js 中引入 uni-well,就可以使用 uni 对象上挂载的所有功能了

import well from 'uni-well';

请求

uni-well 现已初步实现请求模块的开发,通过 uni.$h ,使用 http 模块的功能 ,我们的示例会在项目的根目录下创建 utils/request.js 文件完成请求的配置

const init = () => {
  // 所有请求相关的配置会写在这个函数里面
  // vue3的use方式要求我们导出的应该是一个函数
};
export default init;

通用配置 setConfig

uni.$h.setConfig:通过这个 api 可以设置项目的基本配置,例如服务的地址,超时时间,是否开启遮罩等等

  • 入参:{ Object } 全局通用配置
属性 含义
baseURL 后端服务的请求地址
method 请求方式
dataType 默认 json
responseType: 默认 text

代码示例

const init = () => {
  uni.$h.setConfig({
    // 项目级配置
    baseURL: 'https://fuwuyuming.com.cn', //注意大小写
    header: { token: 'uni-well', entId: '888888', user: 'sun' }
    //TODO : 优化其他可配置参数,例如是否开启请求loading,配置防抖,中断的时间等
  });
};
export default init;

拦截器

请求拦截

请求拦截的请求和响应拦截器作为两个属性分别使用构造器生成,属性名为 interceptor ,重写了原型上的 use 方法,使用时调用 use 注册回调

代码示例

//   请求拦截 在请求发起的时候执行,返回配置属性的完整对象
uni.$h.interceptors.request.use((conf) => {
  conf.header = {
    ...conf.header,
    a: 1
  };
  return conf;
});

响应拦截

uni-well 内部请求的实现参考了 axios 源码的处理方式,链式执行 promise 队列,每执行一次请求,都会从请求拦截开始,直至处理完所有的拦截个接口调用,结束调用

uni-well 提供了两种接口调用的方式,您可以通过自己的喜好选择使用方式或者进行二次封装,如果您不对返回值进行处理,则默认在请求方法的 then 回调中拿到返回值

下面的例子演示同步方式(async/await)调用,返回一个 Promise 的对象

代码示例

//   响应拦截
uni.$h.interceptors.response.use((res) => {
  return Promise.resolve(res.data);
});

发起请求

  • get 方法
  • post 方法

代码示例

onShow: async function () {
    let userInfo = await uni.$h.post(
      "/test/api/login",
      {
        username: "test123",
        password: "qwer1234",
      },
      { header: { a: 2 } }
    );
    console.log("App Show");
  },
// 方法可以抽离集中管理
const getLoginInfo = async () => {
  const data = {
    username: '12344567',
    password: '1234'
  };
  const url = '/login';
  const res = await uni.$h.post(url, data);
  console.log('res:', res);
};
onMounted(() => getLoginInfo());

Readme

Keywords

none

Package Sidebar

Install

npm i uni-well

Weekly Downloads

6

Version

1.0.7

License

MIT

Unpacked Size

31.1 kB

Total Files

24

Last publish

Collaborators

  • geishaalida