项目介绍
效果预览
接口文档
简介
小兔鲜儿是一个以生鲜类产品为主营业务的电商项目
小兔鲜儿技术栈:uni-app、vue3、Pinia、uni-ui
功能介绍
小兔鲜儿是一个以生鲜类产品为主营业务的电商项目,由商品模块、
用户模块以及订单模块 3 大核心模块构成,每个模块下又包含了若干
具体的功能业务。
技术选型
小兔鲜儿项目是以 uni-app 为技术栈的微信小程序,其中包含了动
画、自定义组件、网络通信、本地存储、微信支付等诸多技术要素
项目准备
为 @ 添加代码提示
根目录jsconfig.json
: jsconfig.json
json
{
"compilerOptions": {
"types": ["@dcloudio/types", "miniprogram-api-typings", "mini-types"],
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
vs code 插件准备
公共代码
引入 pinia
官方文档:https://uniapp.dcloud.net.cn/tutorial/vue-vuex.html uni-app中使用pinia: https://uniapp.dcloud.net.cn/tutorial/vue3-pinia.html#状态管理-pinia
封装请求拦截器
目标:每次请求减少基地址的拼写,每次请求自动带上token、每次请求自动解构返回值。
思考:为什么需要自己封装一个 http
发送请求的代码?
以前:
js
const [err, res] = uni.request({
url: 'https://xxxx.com/路径', // 1. 每次要写请求基地址,太麻烦
header: {
Authorization: token // 2. 每次要添加token,太麻烦
}
})
if (err) {
console.log(err)
} else {
console.log(res.data.data) // 3. 每次要解构数组,通过`res.data.data`获取数据
}
问题:
uni-app
中如何封装拦截器
步骤:
新建
src/utils/http.js
jsconst baseURL = "https://pcapi-xiaotuxian-front-devtest.itheima.net"; const interceptor = { // 拦截前触发 - 等价于请求拦截器 invoke(args) { uni.showLoading({ title: "加载中" }); if (!args.url.startsWith("https")) { args.url = baseURL + args.url; } args.header = { ...args.header, // 保留原本的 header "source-client": "miniapp", // 添加小程序端调用标识 }; }, // 完成回调拦截 complete(res) { uni.hideLoading(); }, }; uni.addInterceptor("request", interceptor); uni.addInterceptor("uploadFile", interceptor); const http = async (options) => { const [err, res] = await uni.request(options); if (err) { console.error(err); return; } if (res.statusCode >= 200 && res.statusCode < 300) { return res.data; } if (res.statusCode === 401) { uni.navigateTo({ url: "/pages/login/index" }); return } }; export default http;
vue 组件中使用
vue<script> // 使用 @ 引入组件 import http from "@/utils/http"; export default { async onLoad() { const result = await http({ url: "/home/oneStop/mutli" }); console.log(result); }, }; </script>